Сортировать таблицу по нажатии кнопки

387
27 мая 2017, 16:33

Имеется следующее: данные в таблице появляются из БД SQLite. Требуется при нажатии на кнопку "по названию" сортировать столбец "Название товара" по возрастанию или убыванию.

Код контроллера следующий

package com.lengu.information.systems.lb.two.controller;

public class ProductController {
    @FXML
    public Button nazvButton;
    @FXML
    private Label message = new Label();
    @FXML
    private TextField fieldMinPrice = new TextField ();
    @FXML
    private TextField fieldMaxPrice = new TextField ();
    @FXML
    private TextField fieldMinDiscount = new TextField();
    @FXML
    private TextField fieldMaxDiscount = new TextField();
    @FXML
    private TextField fieldMinBatchQuantity = new TextField();
    @FXML
    private TextField fieldMaxBatchQuantity = new TextField();
    @FXML
    private TableView<Product> productTableView;
    @FXML
    private TableColumn<Product, String> nameProduct;
    @FXML
    private TableColumn<Product, Double> priceProduct;
    @FXML
    private TableColumn<Product, Integer> batchQuantityProduct;
    @FXML
    private TableColumn<Product, Integer> numberProducts;
    @FXML
    private TableColumn<Product, Double> discountProduct;

    private ObservableList<Product> masterData;
    private ProductService productService;
    private List<Product> productList;
    private Product activeProduct;
    @FXML
    private void initialize() {
        productService = new ProductService();
        loadData();
        initFirstValues();
        initTable();
    }

    private void loadData(){
        try {
            productList = productService.getAll();
            activeProduct = productList.get(0);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    private void initTable(){
        masterData = FXCollections.observableArrayList();
        masterData.addAll(productList);
        nameProduct.setCellValueFactory(new PropertyValueFactory<Product, String>("name"));
        priceProduct.setCellValueFactory(new PropertyValueFactory<Product, Double>("price"));
        numberProducts.setCellValueFactory(new PropertyValueFactory<Product, Integer>("number"));
        discountProduct.setCellValueFactory(new PropertyValueFactory<Product, Double>("discount"));
        batchQuantityProduct.setCellValueFactory(new PropertyValueFactory<Product, Integer>("batchQuantity"));
        productTableView.setItems(masterData);
        FilterSupport.addFilter(nameProduct);
    }
    private void initFirstValues(){
        Double minDiscount = productList.get(0).getDiscount();
        Double maxDiscount = 0.0;
        Integer minBatchQuantity = productList.get(0).getBatchQuantity();
        Integer maxBatchQuantity = 0;
        Double minPrice = productList.get(0).getPrice();
        Double maxPrice = 0.0;
        for (Product product : productList){
            if (product.getDiscount() < minDiscount)
                minDiscount = product.getDiscount();
            if (product.getDiscount() > maxDiscount)
                maxDiscount = product.getDiscount();
            if (product.getBatchQuantity() < minBatchQuantity)
                minBatchQuantity = product.getBatchQuantity();
            if (product.getBatchQuantity() > maxBatchQuantity)
                maxBatchQuantity = product.getBatchQuantity();
            if (product.getPrice() < minPrice)
                minPrice = product.getPrice();
            if (product.getPrice() > maxPrice)
                maxPrice = product.getPrice();
        }
        fieldMinDiscount.setText(minDiscount.toString());
        fieldMaxDiscount.setText(maxDiscount.toString());
        fieldMinBatchQuantity.setText(minBatchQuantity.toString());
        fieldMaxBatchQuantity.setText(maxBatchQuantity.toString());
        fieldMinPrice.setText(minPrice.toString());
        fieldMaxPrice.setText(maxPrice.toString());
    }
    @FXML
    public void filtred(){
        loadData();
        message.setText("");
        try {
            Double minDiscount = Double.valueOf(fieldMinDiscount.getText());
            Double maxDiscount = Double.valueOf(fieldMaxDiscount.getText());
            Integer minBatchQuantity = Integer.valueOf(fieldMinBatchQuantity.getText());
            Integer maxBatchQuantity = Integer.valueOf(fieldMaxBatchQuantity.getText());
            Double minPrice = Double.valueOf(fieldMinPrice.getText());
            Double maxPrice = Double.valueOf(fieldMaxPrice.getText());
            List<Product> filtredProductList = new ArrayList<Product>();
            for (Product product : productList) {
                if (product.getDiscount() >= minDiscount && product.getDiscount() <= maxDiscount)
                    if (product.getBatchQuantity() >= minBatchQuantity && product.getBatchQuantity() <= maxBatchQuantity)
                        if (product.getPrice() >= minPrice && product.getPrice() <= maxPrice)
                            filtredProductList.add(product);
            }
            productList = new ArrayList<Product>();
            productList = filtredProductList;
            initTable();
        } catch (Exception e){
            message.setText("Ошибка. Значения фильтров указаны не верно!");
        }
    }
    @FXML
    public void removeFiltred(){
        message.setText("");
        initialize();
    }
    @FXML
    public void openEntry(){
        openWindow("Просмотр товара", "/jfx/view_product.fxml");
    }
    private void openWindow(String title, String path) {
        FXMLLoader loader = new FXMLLoader();
        Parent root = null;
        try {
            root = (Parent) loader.load(getClass().getResourceAsStream(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        ProductDetailsController productDetailsController = loader.getController();
        productDetailsController.setActiveProduct(productTableView.getSelectionModel().getSelectedItem());
        Stage stage = new Stage();
        stage.setTitle(title);
        stage.setResizable(false);
        stage.setScene(new Scene(root));
        stage.show();
    }
    @FXML
    public void onSetNazv(){
    }
}
Answer 1
@FXML
public void onSetNazv() {
    //по возрастанию
    nameProduct.setSortType( TableColumn.SortType.ASCENDING );
    //по убыванию
    //nameProduct.setSortType( TableColumn.SortType.DESCENDING );
    productTableView.getSortOrder().setAll( nameProduct );
}
READ ALSO
Inconvertible types. Достаточно ли это гибкая библиотека,чтобы подстроить под мою ситуацию

Inconvertible types. Достаточно ли это гибкая библиотека,чтобы подстроить под мою ситуацию

Библиотека ASNEПримеры работы с библиотекой и используемый мною код из статьи https://habrahabr

298
JavaFX: IllegalStateException: Location is not set

JavaFX: IllegalStateException: Location is not set

Здравствуйте, никак не могу решить проблемуСоздал окно, в котором есть кнопка, при нажатии на которую должно открываться новое окно

749
JavaFx рисование на ImageView и его подводные камни

JavaFx рисование на ImageView и его подводные камни

У меня есть картинка загружаемая в imageView, я видел примеры что можно рисовать даже на нем, но возможно ли сохранить картинку вместе с изменениями?...

406
Авторизация Firebase

Авторизация Firebase

Почему пользователь Firebase остается зарегистрированным в приложении, после того, как я удалил его из консоли firebase?

280