2013-08-22 71 views
2

我想从TableView中获取选定的项目作为字符串,但它返回整个路径。JavaFx 2 - TableView,返回选定的项目

enter image description here

在上面的图片,当我单击以选中该单元格,我想获得

Indicator selected is: = Shannon Entropy; 

,而我得到

Indicator selected is: ta[email protected]2dafcbf 

这里是我的代码

tableviewIndicators.setOnMousePressed(new EventHandler<MouseEvent>() { 
     @Override 
     public void handle(MouseEvent event) { 
      if (event.isPrimaryButtonDown() && event.getClickCount() == 1) { 

       String indSelected = tableviewIndicators.getSelectionModel().getSelectedItem().toString(); 
       System.out.println("Indicator selected is: " + indSelected);     
      } 
     } 
    }); 
} 

这段代码有什么问题?

谢谢。

+0

你实现了'toString'吗? – tarrsalah

+0

String indSelected = tableviewIndicators.getSelectionModel()。getSelectedItem()。toString(); –

+0

我的意思是代表'TableView'行的overrider'toString'。 – tarrsalah

回答

14

正如我在我的评论中所述,最好使用ChangeListener代替TableView而不是EventHandler<MouseEvent>。这里是一个小的演示:

编辑:Java的8

import javafx.application.Application; 
import javafx.beans.property.SimpleStringProperty; 
import javafx.collections.FXCollections; 
import javafx.collections.ObservableList; 
import javafx.geometry.Insets; 
import javafx.scene.Scene; 
import javafx.scene.control.Label; 
import javafx.scene.control.TableColumn; 
import javafx.scene.control.TableView; 
import javafx.scene.control.cell.PropertyValueFactory; 
import javafx.scene.layout.BorderPane; 
import javafx.scene.layout.HBox; 
import javafx.stage.Stage; 


public class TableDemo extends Application { 

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

    @Override 
    public void start(Stage stage) throws Exception { 
     final Label lblTool = new Label(); 


     HBox hBox = new HBox(); 
     hBox.setSpacing(5.0); 
     hBox.setPadding(new Insets(5, 5, 5, 5)); 
     hBox.getChildren().add(lblTool); 


     final TableView<TableProps> table = new TableView<>(); 

     //Table columns 
     TableColumn<TableProps, String> clmTool = new TableColumn<>("Tool"); 
     clmTool.setMinWidth(160); 
     clmTool.setCellValueFactory(new PropertyValueFactory<>("tool")); 

     TableColumn<TableProps, String> clmChart = new TableColumn<>("Chart"); 
     clmChart.setMinWidth(160); 
     clmChart.setCellValueFactory(new PropertyValueFactory<>("chart")); 

     //Add data 
     final ObservableList<TableProps> data = FXCollections.observableArrayList(
       new TableProps("Volume", ""), 
       new TableProps("Shannon entropy", "") 
     ); 
     table.setItems(data); 
     table.getColumns().addAll(clmTool, clmChart); 

     //Add change listener 
     table.getSelectionModel().selectedItemProperty().addListener((observableValue, oldValue, newValue) -> { 
      //Check whether item is selected and set value of selected item to Label 
      if (table.getSelectionModel().getSelectedItem() != null) { 
       lblTool.setText(newValue.getTool()); 
      } 
     }); 

     BorderPane pane = new BorderPane(); 
     pane.setTop(hBox); 
     pane.setCenter(table); 
     stage.setScene(new Scene(pane, 640, 480)); 
     stage.show(); 

    } 

    public class TableProps { 
     private final SimpleStringProperty tool; 
     private final SimpleStringProperty chart; 

     public TableProps(String tool, String chart) { 
      this.tool = new SimpleStringProperty(tool); 
      this.chart = new SimpleStringProperty(chart); 
     } 

     public String getTool() { 
      return tool.get(); 
     } 

     public SimpleStringProperty toolProperty() { 
      return tool; 
     } 

     public void setTool(String tool) { 
      this.tool.set(tool); 
     } 

     public String getChart() { 
      return chart.get(); 
     } 

     public SimpleStringProperty chartProperty() { 
      return chart; 
     } 

     public void setChart(String chart) { 
      this.chart.set(chart); 
     } 
    } 

} 

您也可能会注意到,当你移动箭头键也可使用。不只是通过点击鼠标。

+0

哪里是表格视图中的复选框.... –

+0

@Reegan这是一个基督耶稣的演示。我不会重建他的整个应用程序。它回答了他的问题,如何选择字符串项目。他不会从复选框返回字符串值。 –

+0

我有一个简单的TableCellCheckBox演示示例代码在那里,我认为这对@Alberto acepsut有用,我会发布该示例代码.... –

0
package tablecellfactorysample; 

import javafx.application.Application; 
import javafx.beans.property.BooleanProperty; 
import javafx.beans.property.SimpleBooleanProperty; 
import javafx.beans.property.SimpleStringProperty; 
import javafx.beans.property.StringProperty; 
import javafx.beans.value.ChangeListener; 
import javafx.beans.value.ObservableValue; 
import javafx.collections.FXCollections; 
import javafx.collections.ObservableList; 
import javafx.event.EventHandler; 
import javafx.geometry.Pos; 
import javafx.scene.Group; 
import javafx.scene.Scene; 
import javafx.scene.control.CheckBox; 
import javafx.scene.control.TableCell; 
import javafx.scene.control.TableColumn; 
import javafx.scene.control.TableColumn.CellEditEvent; 
import javafx.scene.control.TableView; 
import javafx.scene.control.TextField; 
import javafx.scene.control.cell.PropertyValueFactory; 
import javafx.scene.input.KeyCode; 
import javafx.scene.input.KeyEvent; 
import javafx.scene.layout.VBox; 
import javafx.stage.Stage; 
import javafx.util.Callback; 

/** 
* 
* @author reegan 
*/ 
public class TableCellFactorySample extends Application { 

    private void init(Stage primaryStage) { 

     Group root = new Group(); 

     primaryStage.setScene(new Scene(root)); 

     final ObservableList<Person> data = FXCollections.observableArrayList(
       new Person(true, "Jacob", "Smith", "[email protected]"), 
       new Person(false, "Isabella", "Johnson", "[email protected]"), 
       new Person(true, "Ethan", "Williams", "[email protected]"), 
       new Person(true, "Emma", "Jones", "[email protected]"), 
       new Person(true, "Emma", "Jones", "[email protected]"), 
       new Person(false, "Michael", "Brown", "[email protected]")); 

     //"Invited" column 

     TableColumn invitedCol = new TableColumn<Person, Boolean>(); 

     invitedCol.setText("Invited"); 

     invitedCol.setMinWidth(50); 

     invitedCol.setCellValueFactory(new PropertyValueFactory("invited")); 

     invitedCol.setCellFactory(new Callback<TableColumn<Person, Boolean>, TableCell<Person, Boolean>>() { 
      public TableCell<Person, Boolean> call(TableColumn<Person, Boolean> p) { 

       return new CheckBoxTableCell<Person, Boolean>(); 

      } 
     }); 

     //"First Name" column 

     TableColumn firstNameCol = new TableColumn(); 

     firstNameCol.setText("First"); 

     firstNameCol.setCellValueFactory(new PropertyValueFactory("firstName")); 

     //"Last Name" column 

     TableColumn lastNameCol = new TableColumn(); 

     lastNameCol.setText("Last"); 

     lastNameCol.setCellValueFactory(new PropertyValueFactory("lastName")); 

     //"Email" column 

     TableColumn emailCol = new TableColumn(); 

     emailCol.setText("Email"); 

     emailCol.setMinWidth(200); 

     emailCol.setCellValueFactory(new PropertyValueFactory("email")); 



     //Set cell factory for cells that allow editing 

     Callback<TableColumn, TableCell> cellFactory = 
       new Callback<TableColumn, TableCell>() { 
      public TableCell call(TableColumn p) { 

       return new EditingCell(); 

      } 
     }; 

     emailCol.setCellFactory(cellFactory); 

     firstNameCol.setCellFactory(cellFactory); 

     lastNameCol.setCellFactory(cellFactory); 



     //Set handler to update ObservableList properties. Applicable if cell is edited 

     updateObservableListProperties(emailCol, firstNameCol, lastNameCol); 



     TableView tableView = new TableView(); 

     tableView.setItems(data); 

     //Enabling editing 

     VBox vb = new VBox(); 

     tableView.setEditable(true); 

     tableView.getColumns().addAll(invitedCol, firstNameCol, lastNameCol, emailCol); 


     CheckBox cb = new CheckBox("Select all"); 
     cb.selectedProperty().addListener(new ChangeListener<Boolean>() { 
      public void changed(ObservableValue<? extends Boolean> ov, 
        Boolean old_val, Boolean new_val) { 
       if (new_val) { 
        for (Person p : data) { 
         p.invited.set(true); 
        } 

       } 


      } 
     }); 


     vb.getChildren().addAll(cb, tableView); 
     root.getChildren().addAll(vb); 

    } 

    private void updateObservableListProperties(TableColumn emailCol, TableColumn firstNameCol, 
      TableColumn lastNameCol) { 

     //Modifying the email property in the ObservableList 

     emailCol.setOnEditCommit(new EventHandler<CellEditEvent<Person, String>>() { 
      @Override 
      public void handle(CellEditEvent<Person, String> t) { 

       ((Person) t.getTableView().getItems().get(
         t.getTablePosition().getRow())).setEmail(t.getNewValue()); 

      } 
     }); 

     //Modifying the firstName property in the ObservableList 

     firstNameCol.setOnEditCommit(new EventHandler<CellEditEvent<Person, String>>() { 
      @Override 
      public void handle(CellEditEvent<Person, String> t) { 

       ((Person) t.getTableView().getItems().get(
         t.getTablePosition().getRow())).setFirstName(t.getNewValue()); 

      } 
     }); 

     //Modifying the lastName property in the ObservableList 

     lastNameCol.setOnEditCommit(new EventHandler<CellEditEvent<Person, String>>() { 
      @Override 
      public void handle(CellEditEvent<Person, String> t) { 

       ((Person) t.getTableView().getItems().get(
         t.getTablePosition().getRow())).setLastName(t.getNewValue()); 

      } 
     }); 

    } 

    //Person object 
    public static class Person { 

     private BooleanProperty invited; 
     private StringProperty firstName; 
     private StringProperty lastName; 
     private StringProperty email; 

     private Person(boolean invited, String fName, String lName, String email) { 

      this.invited = new SimpleBooleanProperty(invited); 

      this.firstName = new SimpleStringProperty(fName); 

      this.lastName = new SimpleStringProperty(lName); 

      this.email = new SimpleStringProperty(email); 

      this.invited = new SimpleBooleanProperty(invited); 



      this.invited.addListener(new ChangeListener<Boolean>() { 
       public void changed(ObservableValue<? extends Boolean> ov, Boolean t, Boolean t1) { 

        System.out.println(firstNameProperty().get() + " invited: " + t1); 

       } 
      }); 

     } 

     public BooleanProperty invitedProperty() { 
      return invited; 
     } 

     public StringProperty firstNameProperty() { 
      return firstName; 
     } 

     public StringProperty lastNameProperty() { 
      return lastName; 
     } 

     public StringProperty emailProperty() { 
      return email; 
     } 

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

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

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

    //CheckBoxTableCell for creating a CheckBox in a table cell 
    public static class CheckBoxTableCell<S, T> extends TableCell<S, T> { 

     private final CheckBox checkBox; 
     private ObservableValue<T> ov; 

     public CheckBoxTableCell() { 

      this.checkBox = new CheckBox(); 

      this.checkBox.setAlignment(Pos.CENTER); 



      setAlignment(Pos.CENTER); 

      setGraphic(checkBox); 

     } 

     @Override 
     public void updateItem(T item, boolean empty) { 

      super.updateItem(item, empty); 

      if (empty) { 

       setText(null); 

       setGraphic(null); 

      } else { 

       setGraphic(checkBox); 

       if (ov instanceof BooleanProperty) { 

        checkBox.selectedProperty().unbindBidirectional((BooleanProperty) ov); 

       } 

       ov = getTableColumn().getCellObservableValue(getIndex()); 

       if (ov instanceof BooleanProperty) { 

        checkBox.selectedProperty().bindBidirectional((BooleanProperty) ov); 

       } 

      } 

     } 
    } 

    // EditingCell - for editing capability in a TableCell 
    public static class EditingCell extends TableCell<Person, String> { 

     private TextField textField; 

     public EditingCell() { 
     } 

     @Override 
     public void startEdit() { 

      super.startEdit(); 



      if (textField == null) { 

       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.setOnKeyReleased(new EventHandler<KeyEvent>() { 
       @Override 
       public void handle(KeyEvent t) { 

        if (t.getCode() == KeyCode.ENTER) { 

         commitEdit(textField.getText()); 

        } else if (t.getCode() == KeyCode.ESCAPE) { 

         cancelEdit(); 

        } 

       } 
      }); 

     } 

     private String getString() { 

      return getItem() == null ? "" : getItem().toString(); 

     } 
    } 

    @Override 
    public void start(Stage primaryStage) throws Exception { 

     init(primaryStage); 

     primaryStage.show(); 

    } 

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