如何在TableView JavaFx中对列进行排序?

时间:2015-02-16 15:12:38

标签: sorting tableview javafx-8

我尝试通过单击列标题对列进行排序。问题是他没有对定义为Integer的列进行排序。 我为Integer编写了比较器,但我认为这不是对列进行排序的方法。

以下代码属于客户:

public class Client4 extends Application
{ // IO streams
private DataOutputStream toServer = null;
private DataInputStream fromServer = null;
private TableView<Student> tableView = new TableView<Student>();
private ObservableList<Student> data = FXCollections.observableArrayList();
private ComboBox<String> cboStudent = new ComboBox<>();
private ComboBox<String> cboLecturer = new ComboBox<>();
private ArrayList<TableColumn> tableCol = new ArrayList<TableColumn>();
private Callback<TableColumn<Student, String>, TableCell<Student, String>> cellFactory
= (TableColumn<Student, String> p) -> new EditingCell();
@Override // Override the start method in the Application class
public void start(Stage primaryStage)  throws Exception
{ // Panel p to hold the label and text field
    Button btAddRow = new Button("Add Student");
    Button btDeleteRow = new Button("Delete Student");
    Button btEdit = new Button("Edit");
    Button btAddColumn = new Button("Add Column");
    Button btDeleteColumn = new Button("Delete Column");
    tableView.setItems(data);
    //tableView.setEditable(true);
    //      Callback<TableColumn<Student, String>, TableCell<Student, String>> cellFactory
    //            = (TableColumn<Student, String> p) -> new EditingCell();

    BorderPane pane = new BorderPane();
    pane.setPadding(new Insets(11.5, 12.5, 13.5, 14.5)); 
    HBox hBox = new HBox(20);

    hBox.getChildren().addAll(btAddRow, btDeleteRow, 
            btEdit, btAddColumn, btDeleteColumn);
    pane.setTop(hBox);
    try {

        //  @SuppressWarnings("resource")
        Socket socket = new Socket("localhost", 8000);
        // Create an input stream to receive data from the server
        fromServer = new DataInputStream(socket.getInputStream());
        // Create an output stream to send data to the server
        toServer = new DataOutputStream(socket.getOutputStream());
        ArrayList<String> lables = new ArrayList<String>();
        int numberRecords=0;
        numberRecords = fromServer.readInt();
        System.out.println(numberRecords);
        while (numberRecords>0)
        {   String record =fromServer.readUTF();
        lables.add(record);
        cboStudent.getItems().add(record);
        numberRecords--;
        }
        for(int i=0; i<lables.size();i++)
        {
            String lable = lables.get(i);
            TableColumn<Student, String> string = new TableColumn<Student, String>(lable);
            string.setMinWidth(100);
            if (lable.equals("firstName") || lable.equals("lastName") || lable.equals("city") || lable.equals("street") || lable.equals("dept") )
            {               
                string.setCellValueFactory(
                        new PropertyValueFactory<Student, String>(lable));
                defineCell(string);

                //                  ObservableList<String> cbValues = FXCollections.observableArrayList("1", "2", "3");
                //                  string.setCellFactory(ComboBoxTableCell.forTableColumn(new DefaultStringConverter(), cbValues));
                tableView.getColumns().add(string);
                tableCol.add(string);
            }
            else if(lable.equals("birthDate"))
            {
                TableColumn<Student, Date> date = new TableColumn<Student, Date>(lable);
                date.setCellValueFactory(
                        new PropertyValueFactory<Student, Date>(lable));
                //defineCell(date);
                tableView.getColumns().add(date);
                tableCol.add(date);
            }
            else if(lable.equals("picture"))
            {
                TableColumn<Student, ImageView> pic = new TableColumn<Student, ImageView>(lable);
                pic.setCellValueFactory(
                        new PropertyValueFactory<Student, ImageView>(lable));
                tableView.getColumns().add(pic);
                tableCol.add(pic);
            }
            else 
            {
                TableColumn<Student, Integer> integer = new TableColumn<Student, Integer>(lable);
                integer.setCellValueFactory(
                        new PropertyValueFactory<Student, Integer>(lable));
                integer.setSortable(true);
                integer.setComparator(new Comparator<Integer>() {

                    @Override
                    public int compare(Integer o1, Integer o2) {
                        if(o1<o2) return 1;
                        if(o1>o2)return -1;
                        return 0;
                    }
                });

                tableView.getColumns().add(integer);
                tableCol.add(integer);
            }


        }
        numberRecords=0;
        numberRecords=fromServer.readInt();
        while(numberRecords>0)
        {   Student student = new Student();
        student.setId(fromServer.readUTF());
        student.setFirstName(fromServer.readUTF());
        student.setLastName(fromServer.readUTF());
        student.setCity(fromServer.readUTF());
        student.setStreet(fromServer.readUTF());
        student.setHouseNumber(fromServer.readUTF());
        student.setZipCode(fromServer.readUTF());
        student.setBirthDate(fromServer.readUTF());
        student.setPicture(fromServer.readUTF());
        student.setStartYear(fromServer.readUTF());
        student.setDept(fromServer.readUTF());
        student.setCredits(fromServer.readUTF());
        student.setAverage(fromServer.readUTF());
        student.setNumFailed(fromServer.readUTF());
        student.setPlace(fromServer.readUTF());
        System.out.println(student);
        data.add(student);
        numberRecords--;
        }
        tableView.setItems(data);
    }
    catch (IOException ex) {

    }

    btEdit.setOnAction(e -> {
        editTable(btEdit.toString());

    });


    pane.setBottom(tableView);
    Scene scene = new Scene(pane, 890, 400);
    primaryStage.setTitle("ShowCombination"); // Set the stage title
    primaryStage.setScene(scene); // Place the scene in the stage
    primaryStage.show(); // Display the stage  
    primaryStage.setAlwaysOnTop(true);
}

private void defineCell(TableColumn<Student, String> string) {
    string.setCellFactory(cellFactory);        
    string.setOnEditCommit(
            (CellEditEvent<Student, String> t) -> {
                ((Student) t.getTableView().getItems().get(
                        t.getTablePosition().getRow())
                        ).setFirstName(t.getNewValue());
            });

    ObservableList<String> cbValues = FXCollections.observableArrayList("1", "2", "3");
    string.setCellFactory(ComboBoxTableCell.forTableColumn(new DefaultStringConverter(), cbValues));        

}

private void editTable(String string) {
    tableView.setEditable(true);
    Student student=(Student)tableView.getSelectionModel().getSelectedItem();

}

public static void main(String[] args)
{ launch(args);
}
class EditingCell extends TableCell<Student, String> {

    private TextField textField;

    public EditingCell() {
    }

    @Override
    public void startEdit() {
        if (!isEmpty()) {
            super.startEdit();
            createTextField();
            setText(null);
            setGraphic(textField);
            textField.selectAll();
        }
    }

    @Override
    public void cancelEdit() {
        super.cancelEdit();

        setText((String) getItem());
        setGraphic(null);
    }

    @Override
    public void updateItem(String item, boolean empty) {
        super.updateItem(item, empty);

        if (empty) {
            setText(null);
            setGraphic(null);
        } else {
            if (isEditing()) {
                if (textField != null) {
                    textField.setText(getString());
                }
                setText(null);
                setGraphic(textField);
            } else {
                setText(getString());
                setGraphic(null);
            }
        }
    }

    private void createTextField() {
        textField = new TextField(getString());
        textField.setMinWidth(this.getWidth() - this.getGraphicTextGap()* 2);
        textField.focusedProperty().addListener(
                (ObservableValue<? extends Boolean> arg0, 
                        Boolean arg1, Boolean arg2) -> {
                            if (!arg2) {
                                commitEdit(textField.getText());
                            }
                        });
    }

    private String getString() {
        return getItem() == null ? "" : getItem().toString();
    }
}
}

2 个答案:

答案 0 :(得分:1)

您需要将ObservableList TableView数据保存在SortedList

SortedList<Student> sortedItems = new SortedList<>(data);
tableView.setItems(sortedItems);

接下来,您需要将两者链接在一起:

sortedItems.comparatorProperty().bind(tableView.comparatorProperty());

作为一个友好的旁注:请考虑发布一个较小的代码示例,仅显示证明您的问题的必要条件; - )

答案 1 :(得分:0)

正如James_D所说,立方根将以相同的顺序排序,但这里有一个小例子可以用来展示你想要做的事情

import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javafx.application.Application;
import javafx.beans.property.ReadOnlyObjectWrapper;
import javafx.collections.FXCollections;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.stage.Stage;

public class TableSort extends Application {

    @Override
    public void start(Stage primaryStage) {
        TableView tv = new TableView(FXCollections.observableArrayList(
                IntStream.of(1,-2,3,-4,-5,6)
                        .map(n->{return (int)Math.pow(n, 3);})
                        .boxed().collect(Collectors.toList())));

        TableColumn<Integer, Integer> numCol = new TableColumn("num");
        numCol.setCellValueFactory((param) -> {
            return new ReadOnlyObjectWrapper<>(param.getValue());
        });

        TableColumn<Integer, Integer> cbrtCol = new TableColumn("cube root");
        cbrtCol.setCellValueFactory((param) -> {
            return new ReadOnlyObjectWrapper<>((int)Math.cbrt(param.getValue()));
        });

        numCol.setComparator((Integer o1, Integer o2) -> {
            return Double.compare(Math.cbrt(o1), Math.cbrt(o2));
        });

        tv.getColumns().addAll(numCol, cbrtCol);

        Scene scene = new Scene(tv);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}