当前位置: 首页 > 知识库问答 >
问题:

通过拖放对tableview进行排序(行)

姜明贤
2023-03-14

我的目标是通过拖放对tableview进行排序。我举了一个例子:http://docs.oracle.com/javafx/2/fxml_get_started/fxml_tutorial_intermediate.htm

对于拖放,我通过Scene Builder添加了fxml

<TableView fx:id="tableView" onDragDetected="#dragDetected" onDragDropped="#dragDropped" onDragOver="#dragOver"

制造了控制器

@FXML
    private void dragDetected(MouseEvent event) {
        System.out.println("dragDetected");

        Integer idx;
        idx = tableView.getSelectionModel().getFocusedIndex();
        Dragboard db = tableView.startDragAndDrop(TransferMode.MOVE);
        ClipboardContent content = new ClipboardContent();
        content.putString(idx.toString());
        db.setContent(content);

        System.out.println(idx);
//        System.out.println(event.getPickResult());
        event.consume();
    }

    @FXML
    private void dragOver(DragEvent event) {
        event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
        event.consume();
    }

    @FXML
    private void dragDropped(DragEvent event) {
        System.out.println("dragDropped");

        System.out.println(event.getTarget());
        System.out.println(event.getPickResult());
    }

但是在drag Drop,我无法得到我扔下物体的那排位置。我得到的只是手机信息<代码>文本[Text=“Smith”,x=0.0,y=0.0,…

我怎样才能得到这份工作?也许Class TableRow


共有3个答案

王彭薄
2023-03-14

将1个答案(从James_D)转换为FMXL:

public class FXMLTableViewController implements Initializable {
    private static final DataFormat SERIALIZED_MIME_TYPE = new DataFormat("application/x-java-serialized-object");

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        tableView.setRowFactory(tv -> {
        ...
            return row ;
        });
    }

    @FXML
    private TableView<Person> tableView;
    ...

索嘉胜
2023-03-14

使用来自@James_D的答案,我还创建了一个多选择验证。

import java.util.ArrayList;
import java.util.function.Function;

import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.scene.Scene;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.DataFormat;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;
public class TableViewDragRows2 extends Application {

    private static final DataFormat SERIALIZED_MIME_TYPE = new DataFormat("application/x-java-serialized-object");
    private ArrayList<Person> selections = new ArrayList<>();
    @Override
    public void start(Stage primaryStage) {
        TableView<Person> tableView = new TableView<>();
        tableView.getColumns().add(createCol("First Name", Person::firstNameProperty, 150));
        tableView.getColumns().add(createCol("Last Name", Person::lastNameProperty, 150));
        tableView.getColumns().add(createCol("Email", Person::emailProperty, 200));
        tableView.getColumns().add(createCol("Country", Person::countryProperty, 200));
        tableView.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
        tableView.getItems().addAll(
            new Person("Jacob", "Smith", "jacob.smith@example.com","A"),
            new Person("Isabella", "Johnson", "isabella.johnson@example.com","A"),
            new Person("Ethan", "Williams", "ethan.williams@example.com","A"),
            new Person("Emma", "Jones", "emma.jones@example.com","B"),
            new Person("da", "Jones", "emma.jones@example.com","B"),
            new Person("csd", "Jones", "emma.jones@example.com","B"),
            new Person("dsf", "Jones", "emma.jones@example.com","B"),
            new Person("fsd", "Jones", "emma.jones@example.com","B"),
            new Person("feferef", "Jones", "emma.jones@example.com","B"),
            new Person("Michael", "Brown", "michael.brown@example.com","C"),
            new Person("XMan", "Brown", "michael.brown@example.com","C"),
            new Person("ZMan", "Brown", "michael.brown@example.com","D"),
            new Person("YMan", "Brown", "michael.brown@example.com","D"),
            new Person("DDDMan", "Brown", "michael.brown@example.com","D")
        );

        tableView.setRowFactory(tv -> {
            TableRow<Person> row = new TableRow<>();

            row.setOnDragDetected(event -> {
                if (! row.isEmpty()) {
                    Integer index = row.getIndex();

                    selections.clear();//important...

                    ObservableList<Person> items = tableView.getSelectionModel().getSelectedItems();

                    for(Person iI:items) {
                        selections.add(iI);
                    }


                    Dragboard db = row.startDragAndDrop(TransferMode.MOVE);
                    db.setDragView(row.snapshot(null, null));
                    ClipboardContent cc = new ClipboardContent();
                    cc.put(SERIALIZED_MIME_TYPE, index);
                    db.setContent(cc);
                    event.consume();
                }
            });

            row.setOnDragOver(event -> {
                Dragboard db = event.getDragboard();
                if (db.hasContent(SERIALIZED_MIME_TYPE)) {
                    if (row.getIndex() != ((Integer)db.getContent(SERIALIZED_MIME_TYPE)).intValue()) {
                        event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
                        event.consume();
                    }
                }
            });

            row.setOnDragDropped(event -> {
                Dragboard db = event.getDragboard();

                if (db.hasContent(SERIALIZED_MIME_TYPE)) {

                    int dropIndex;Person dI=null; 

                    if (row.isEmpty()) {
                        dropIndex = tableView.getItems().size() ;
                    } else {
                        dropIndex = row.getIndex();
                        dI = tableView.getItems().get(dropIndex);
                    }
                    int delta=0;
                    if(dI!=null)
                    while(selections.contains(dI)) {
                        delta=1;
                        --dropIndex;
                        if(dropIndex<0) {
                            dI=null;dropIndex=0;
                            break;
                        }
                        dI = tableView.getItems().get(dropIndex);
                    }

                    for(Person sI:selections) {
                        tableView.getItems().remove(sI);
                    }

                    if(dI!=null)
                        dropIndex=tableView.getItems().indexOf(dI)+delta;
                    else if(dropIndex!=0)
                        dropIndex=tableView.getItems().size();



                    tableView.getSelectionModel().clearSelection();

                    for(Person sI:selections) {
                        //draggedIndex = selections.get(i);
                        tableView.getItems().add(dropIndex, sI);
                        tableView.getSelectionModel().select(dropIndex);
                        dropIndex++;

                    }

                    event.setDropCompleted(true);
                    selections.clear();
                    event.consume();
                }
            });

            return row ;
        });


        Scene scene = new Scene(new BorderPane(tableView), 600, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private TableColumn<Person, String> createCol(String title, 
            Function<Person, ObservableValue<String>> mapper, double size) {

        TableColumn<Person, String> col = new TableColumn<>(title);
        col.setCellValueFactory(cellData -> mapper.apply(cellData.getValue()));
        col.setPrefWidth(size);

        return col ;
    }


   public class Person {
        private final StringProperty firstName = new SimpleStringProperty(this, "firstName");
        private final StringProperty lastName = new SimpleStringProperty(this, "lastName");
        private final StringProperty email = new SimpleStringProperty(this, "email");
        private final StringProperty country = new SimpleStringProperty(this, "country");;

        public Person(String firstName, String lastName, String email, String country) {
            this.firstName.set(firstName);
            this.lastName.set(lastName);
            this.email.set(email);
            this.country.set(country);
        }

        public final StringProperty firstNameProperty() {
            return this.firstName;
        }

        public final String getFirstName() {
            return this.firstNameProperty().get();
        }

        public final void setFirstName(final String firstName) {
            this.firstNameProperty().set(firstName);
        }

        public final StringProperty lastNameProperty() {
            return this.lastName;
        }

        public final String getLastName() {
            return this.lastNameProperty().get();
        }

        public final void setLastName(final String lastName) {
            this.lastNameProperty().set(lastName);
        }

        public final StringProperty emailProperty() {
            return this.email;
        }
        public final StringProperty countryProperty() {
            return this.country;
        }

        public final String getEmail() {
            return this.emailProperty().get();
        }

        public final void setEmail(final String email) {
            this.emailProperty().set(email);
        }

    }

    public static void main(String[] args) {
        launch(args);
    }
}
昌勇锐
2023-03-14

正如您所怀疑的,答案是使用TableRow。您可以通过在表上设置行工厂来做到这一点,该工厂用于根据需要创建表行。您可以创建它们并在返回它们之前设置它们的拖动处理程序。

因此,从FXML中删除onDragDetectedondragDrop等属性,并在控制器的初始化方法中设置行上的拖动处理程序。

这是一个完整的示例,使用Oracle教程中的常用示例。我在这个示例中没有使用FXML(我只是直接在Java类中创建了表视图),但是您可以将所有表视图配置移动到初始化方法。

import java.util.function.Function;

import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.beans.value.ObservableValue;
import javafx.scene.Scene;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableRow;
import javafx.scene.control.TableView;
import javafx.scene.input.ClipboardContent;
import javafx.scene.input.DataFormat;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class TableViewDragRows extends Application {

    private static final DataFormat SERIALIZED_MIME_TYPE = new DataFormat("application/x-java-serialized-object");

    @Override
    public void start(Stage primaryStage) {
        TableView<Person> tableView = new TableView<>();
        tableView.getColumns().add(createCol("First Name", Person::firstNameProperty, 150));
        tableView.getColumns().add(createCol("Last Name", Person::lastNameProperty, 150));
        tableView.getColumns().add(createCol("Email", Person::emailProperty, 200));

        tableView.getItems().addAll(
            new Person("Jacob", "Smith", "jacob.smith@example.com"),
            new Person("Isabella", "Johnson", "isabella.johnson@example.com"),
            new Person("Ethan", "Williams", "ethan.williams@example.com"),
            new Person("Emma", "Jones", "emma.jones@example.com"),
            new Person("Michael", "Brown", "michael.brown@example.com")
        );

        tableView.setRowFactory(tv -> {
            TableRow<Person> row = new TableRow<>();

            row.setOnDragDetected(event -> {
                if (! row.isEmpty()) {
                    Integer index = row.getIndex();
                    Dragboard db = row.startDragAndDrop(TransferMode.MOVE);
                    db.setDragView(row.snapshot(null, null));
                    ClipboardContent cc = new ClipboardContent();
                    cc.put(SERIALIZED_MIME_TYPE, index);
                    db.setContent(cc);
                    event.consume();
                }
            });

            row.setOnDragOver(event -> {
                Dragboard db = event.getDragboard();
                if (db.hasContent(SERIALIZED_MIME_TYPE)) {
                    if (row.getIndex() != ((Integer)db.getContent(SERIALIZED_MIME_TYPE)).intValue()) {
                        event.acceptTransferModes(TransferMode.COPY_OR_MOVE);
                        event.consume();
                    }
                }
            });

            row.setOnDragDropped(event -> {
                Dragboard db = event.getDragboard();
                if (db.hasContent(SERIALIZED_MIME_TYPE)) {
                    int draggedIndex = (Integer) db.getContent(SERIALIZED_MIME_TYPE);
                    Person draggedPerson = tableView.getItems().remove(draggedIndex);

                    int dropIndex ; 

                    if (row.isEmpty()) {
                        dropIndex = tableView.getItems().size() ;
                    } else {
                        dropIndex = row.getIndex();
                    }

                    tableView.getItems().add(dropIndex, draggedPerson);

                    event.setDropCompleted(true);
                    tableView.getSelectionModel().select(dropIndex);
                    event.consume();
                }
            });

            return row ;
        });


        Scene scene = new Scene(new BorderPane(tableView), 600, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private TableColumn<Person, String> createCol(String title, 
            Function<Person, ObservableValue<String>> mapper, double size) {

        TableColumn<Person, String> col = new TableColumn<>(title);
        col.setCellValueFactory(cellData -> mapper.apply(cellData.getValue()));
        col.setPrefWidth(size);

        return col ;
    }


   public class Person {
        private final StringProperty firstName = new SimpleStringProperty(this, "firstName");
        private final StringProperty lastName = new SimpleStringProperty(this, "lastName");
        private final StringProperty email = new SimpleStringProperty(this, "email");

        public Person(String firstName, String lastName, String email) {
            this.firstName.set(firstName);
            this.lastName.set(lastName);
            this.email.set(email);
        }

        public final StringProperty firstNameProperty() {
            return this.firstName;
        }

        public final String getFirstName() {
            return this.firstNameProperty().get();
        }

        public final void setFirstName(final String firstName) {
            this.firstNameProperty().set(firstName);
        }

        public final StringProperty lastNameProperty() {
            return this.lastName;
        }

        public final String getLastName() {
            return this.lastNameProperty().get();
        }

        public final void setLastName(final String lastName) {
            this.lastNameProperty().set(lastName);
        }

        public final StringProperty emailProperty() {
            return this.email;
        }

        public final String getEmail() {
            return this.emailProperty().get();
        }

        public final void setEmail(final String email) {
            this.emailProperty().set(email);
        }

    }

    public static void main(String[] args) {
        launch(args);
    }
}
 类似资料:
  • 问题内容: 我想具有重新排列表中的行的功能(使用拖放对行进行排序)。 并且行排列的索引在模型中也应更改。 如何 使用Angular Directive 做类似的事情:http : //jsfiddle.net/tzYbU/1162/? 我正在生成表为: 问题答案: 我做的。请参阅下面的代码。 的HTML 指令(JS)

  • 你可以使用内置的 yield* 操作符来组合多个 Sagas,使得它们保持顺序。 这让你可以一种简单的程序风格来排列你的 宏观任务(macro-tasks)。 function* playLevelOne(getState) { ... } function* playLevelTwo(getState) { ... } function* playLevelThree(getState) { .

  • 我有两张紧挨着的桌子。以下是模板的一个简短示例: 看起来是这样的: 我的目标是使用可排序的jquery-ui功能,通过同时拖放两个表的行来排序。换句话说-当用户单击例如从tabel1单元格然后整行 当鼠标向上时,应先拖动,然后再放下。我不需要在两个表之间拖放行—我需要在拖动时将两个表中的行视为一行—如果这些行在其表中具有相同的位置Y。 实际上,用例是我有网格,我需要在其中实现拖放行。用户可以冻结网

  • 问题内容: 这是我当前模型的简化示例(我正在使用Flask SQLAlchemy扩展): 我正在尝试按喜欢的次数订购。 这是我基本上想发出的查询: 我只是无法在SQLAlchemy方面进行任何工作。 感谢您提供任何帮助。 问题答案: 我没有使用SQLAlchemy,所以我想尝试一下。我没有尝试使用你的模型,我只是写了一些新模型(尽管足够类似): 你想要加入likes表格,用于func.count计

  • 免责声明:我已经发布过这样一个问题,它被标记为重复。请帮帮我。我已经看过了stackoverflow之前的所有方法,但都没有任何帮助。在我的例子中,提到的所有对Map(Key,Values)进行排序的方法都不起作用,因为我还有一个步骤,即检索值的属性。这一次,我试着详细讲述。 我有一个地图(字符串,对象)在Java,我想排序它使用对象的属性之一。 假设我有一堂课 现在,我创建了一张地图 我想通过类