Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

javafx tableview how to get the row I clicked?

here is my code

// this event is attached to TableCell
public EventHandler dblclickDescription = new EventHandler<MouseEvent>(){
    @Override
    public void handle(MouseEvent event) {
        if(event.getButton().equals(MouseButton.PRIMARY)){
            if(event.getClickCount() == 2){
                printRow(event.getTarget());
            }
        }
        event.consume();
    }
};

// print row
public void printRow(Object o){
    Text text = (Text) o;

    // ??? don't know what to write here

   System.out.println(row.toString());
}

1) how do I get from the cell I clicked to the row?

2) can I attach the event to the whole row instead of each column?

EDIT: 3) I thought that I attached the event on TableCell

TableCell cell = TableColumn.DEFAULT_CELL_FACTORY.call(p);
cell.setOnMouseClicked(dblclickDescription);

but when I tested,

event.getSource();// is a TableColumn
event.getTarget();// is a Text if clicked on text
event.getTarget();// is a TableColumn if clicked on empty space, even if that cell has text

is there a way to get TableCell from MouseEvent?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

To answer your specific questions:

how do I get from the cell I clicked to the row?

TableCell defines a getTableRow() method, returning the TableRow. So you can do

Object item = cell.getTableRow().getItem();

which will give you the row item from the table (i.e. the correct element of table.getItems()). You can also get this from table.getItems().get(cell.getIndex()) if you prefer.

can I attach the event to the whole row instead of each column?

Yes. Define a rowFactory:

TableView<MyDataType> table = new TableView<>();

table.setRowFactory(tv -> {
    TableRow<MyDataType> row = new TableRow<>();
    row.setOnMouseClicked(event -> {
        if (! row.isEmpty() && event.getButton()==MouseButton.PRIMARY 
             && event.getClickCount() == 2) {

            MyDataType clickedRow = row.getItem();
            printRow(clickedRow);
        }
    });
    return row ;
});

// ...

private void printRow(MyDataType item) {
    // ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...