Javafx SceneBuilder Tableview.getSelectionModel无效

时间:2015-06-05 21:28:51

标签: javafx scenebuilder

Tableview.getSelectionModel无效。在建议形式@James_D之后,我使用了Model类(软件)来选择我需要的列,同时将SQL拉到tableview。我在这里搜索,网页,移动代码和检查intellisense,我可以在任何地方找到的最好的例子在下面的SoftwareController代码中被注释掉,什么都没有用?

在使用Model类之前,我已经在示例4工作的SoftwareController中进行了操作,它给出了第0列的单元格数据,其中我点击了该行,我用它来提取更多的SQL数据。现在,newValue.get(0)newValue的错误未显示get()或getid可用。

我已将SelectedItem更改为索引并添加了toString以及所有这些,我得到了fxml.software@sometext或行索引。示例1给出了任何单元格的单元格数据,但我只想要我选择的行上的第一列,在我的例子中是一个ID,而不是行索引。 我现在还必须使用@SuppressWarnings进行" Raw"错误,这是因为我在初始化? 任何帮助或指示将不胜感激。

SoftwareController

public class SoftwareController extends Application implements Initializable {
private Statement statement;
Connection conn = null;
@FXML Button  btnSoftware;
@FXML Label lblTest;
@FXML TableView tblSoftware;
@FXML TableColumn CI_IDcol;
@FXML TableColumn Namecol;

public static void main(String[] args) {

    launch(args);

}

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


    FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/Software.fxml")); //load Software fxml file
    Parent root1 = (Parent) fxmlLoader.load();
    primaryStage.setScene(new Scene(root1));
    primaryStage.show();

}

private static ObservableList<Software>data;
@FXML   private TextField txtFilter;
private Object getCellData;

@SuppressWarnings({ "unchecked", "rawtypes" })  //added due to TableView getselecionModel code
@Override
public void initialize(URL location, ResourceBundle resources)  {

    try {

        data = FXCollections.observableArrayList();
        conn = DBconnection.makeConnection();
        statement = conn.createStatement();
        String SQL = "SELECT * FROM Data_CMDB_Main";
        ResultSet rs = statement.executeQuery(SQL);

        while (rs.next())   {
            data.add(new Software(rs.getString("CI_ID"),
                                  rs.getString("Name")));

            CI_IDcol.setCellValueFactory(new PropertyValueFactory("CI_ID"));
            Namecol.setCellValueFactory(new PropertyValueFactory("Name"));
            tblSoftware.setItems(null);
            tblSoftware.setItems(data);

//TableView.selection               
            //get row example 1
            /*tblSoftware.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
            @Override
            public void changed(ObservableValue observableValue, Object oldValue, Object newValue) {
                if(tblSoftware.getSelectionModel().getSelectedItem() != null) {
                    TableViewSelectionModel selectionModel = tblSoftware.getSelectionModel();
                    ObservableList selectedCells = selectionModel.getSelectedCells();
                    TablePosition tablePosition = (TablePosition) selectedCells.get(0);
                    Object val = tablePosition.getTableColumn().getCellData(newValue);
                    //Object val = tblSoftware.getColumns().get(0).toString();
                    System.out.println(val);                    //int row = tablePosition.getRow();

                }                       
                }
            });*/


            //get row example 2   only gives index of filtered rows
            //tblSoftware.getSelectionModel().selectedIndexProperty().addListener((v, oldValue, newValue) -> System.out.println(newValue)); //gets all row data

            //get row example 3 ItemProperty seems correct just not giving readable row identification
            //tblSoftware.getSelectionModel().selectedItemProperty().addListener((v, oldValue, newValue) -> System.out.println(newValue)); //gets all row data


            ///get row example 4
            //@Override
            /*tblSoftware.getSelectionModel().selectedItemProperty().addListener( //gets any row column
                    (observable, oldValue, newValue) -> {
                        if (newValue == null) {
                            lblTest.setText("");
                            return;
                        }

                        lblTest.setText("Selected Number: " + newValue.get(0)); 
                    }
                );*/

            ///get row example 5

            /*tblSoftware.getSelectionModel().selectedItemProperty().addListener( //gets any row column
                    new ChangeListener<IdentifiedName>() {
                        @Override
                        public void changed (
                            ObservableValue<? extends IdentifiedName> observable,
                            IdentifiedName oldValue,
                            IdentifiedName newValue
                        ){
                            if(newValue == null) {
                                lblTest.setText("");
                                return;
                            }

                        lblTest.setText("Selected Number: " + + newValue.getId(0));

                }
            }   
     );             */



//filter        
            txtFilter.setPromptText("Text Filter");
            txtFilter.textProperty().addListener(new InvalidationListener() {

                @Override
                public void invalidated(Observable o)   {
                    tblSoftware.getSelectionModel().clearSelection(); // this gives no errors when switching back to filter box when row previously selected
                    if(txtFilter.textProperty().get().isEmpty())    {
                        tblSoftware.setItems(data);
                        return;
                    }
                    ObservableList<Software> tableItems = FXCollections.observableArrayList();
                    ObservableList<TableColumn<Software, ?>> cols = tblSoftware.getColumns();
                    for(int i=0; i<data.size(); i++)    {

                    for(int j=0; j<cols.size(); j++)    {
                        TableColumn col = cols.get(j);
                        String cellValue = col.getCellData(data.get(i)).toString();
                        cellValue = cellValue.toLowerCase();
                        if(cellValue.contains(txtFilter.textProperty().get().toLowerCase()))    {
                            tableItems.add(data.get(i));
                            break;                  
                        }
                    }

                    } 
                    tblSoftware.setItems(tableItems);
                }
            });
        }               

    } catch (SQLException e) {

        e.printStackTrace();
    }

}


protected void setIndex(int selectedIndex) {
    // TODO Auto-generated method stub

}

public void btnSoftwarePressed(){
    lblTest.setText("Button works");


}
}

软件类

 package fxml;
 import javafx.beans.property.SimpleStringProperty;
 import javafx.beans.property.StringProperty;


public class Software {

    private StringProperty CI_ID;
    private StringProperty Name;

    public Software(String CI_ID, String Name)  {
        this.CI_ID = new SimpleStringProperty(CI_ID);
        this.Name = new SimpleStringProperty(Name);
    }

    public StringProperty CI_IDProperty()   {
        return CI_ID;
    }

    public StringProperty NameProperty()    {
        return Name;
    }
}

软件fxml

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.*?>
<?import javafx.scene.text.*?>
<?import java.lang.*?>
<?import java .util.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>


<BorderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="fxml.SoftwareController">
   <center>
      <TableView fx:id="tblSoftware" prefHeight="200.0" prefWidth="600.0" BorderPane.alignment="CENTER">
        <columns>
          <TableColumn fx:id="CI_IDcol" prefWidth="100.0" text="CI_ID" />
          <TableColumn fx:id="Namecol" prefWidth="150.0" text="Name" />
        </columns>
      </TableView>
   </center>
   <top>
      <VBox prefHeight="83.0" prefWidth="600.0" BorderPane.alignment="CENTER">
         <children>
            <HBox prefHeight="100.0" prefWidth="200.0">
               <children>
                  <Button fx:id="btnSoftware" mnemonicParsing="false" onAction="#btnSoftwarePressed" text="Button" />
                  <Label fx:id="lblTest" prefHeight="28.0" prefWidth="158.0" text="Label" />
                  <ParallelCamera />
               </children>
            </HBox>
            <HBox>
               <children>
                  <TextField fx:id="txtFilter" />
               </children>
            </HBox>
         </children>
      </VBox>
   </top>
</BorderPane>

1 个答案:

答案 0 :(得分:0)

我不确定你想要做什么,但是我可以给你我的方法将数据从db插入到tableview中,之后,使用之前加载的数据从db获取数据进入tableview。

我首先在控制器中创建了一个内部类,它将代表从数据库中保存/加载的实例:

public static class Detector {
    private String name;
    private String conn_type;
    private int num_detect;
    private String serial_port;
    private int data_bits;
    private int stop_bits;
    private String parity;
    private String ip;
    private int eth_port;
    private int historic;

    public Detector(String name, String conn_type, int num_detect, String serial_port, int speed,
        int data_bits, int stop_bits, String parity, String ip, int eth_port, int his){

        this.name = name;
        this.conn_type = conn_type;
        this.num_detect = num_detect;
        this.serial_port = serial_port;
        this.data_bits = data_bits;
        this.stop_bits = stop_bits;
        this.parity = parity;
        this.ip = ip;
        this.eth_port = eth_port;
        this.historic = his;
    }
}

除此之外,我宣布了tableview

public class Controller implements Initializable {
   @FXML
   private TableView<Detector> detectors; 
   .
   .
   .

我使用从查询中获得的数据创建了tableview:

    DBConnection c = new DBConnection();
    c.connect();
    try{
        String sql = "select * from detector order by name";
        ResultSet rs = c.query(sql);

        ObservableList<Detector> data = FXCollections.observableArrayList();
        while(rs.next()){               
            data.add(new Detector(rs.getString("name"),
                                    rs.getString("conn_type"),                                     
                                    Integer.parseInt(rs.getString("num_detect")),
                                    rs.getString("serial_port"),
                                    Integer.parseInt(rs.getString("speed")),
                                    Integer.parseInt(rs.getString("data_bits")),
                                    Integer.parseInt(rs.getString("stop_bits")),
                                    rs.getString("parity"),
                                    rs.getString("ip"),
                                    Integer.parseInt(rs.getString("puerto_socket")),
                                    Integer.parseInt(rs.getString("historico"))
            ));
        }
        TableColumn colName = new TableColumn("Name");
        colName.setCellValueFactory(new PropertyValueFactory<Detector, String>("name"));
        detectors.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> loadName(newValue));
        detectors.setItems(data);
        detectors.getColumns().addAll(nombreCol);           
        //Add a column for every column data you want to show

然后,您必须定义侦听器调用的方法的行为(在我的情况下,&#34; loadName&#34;)

private void loadName(Detector r){
    //here you could, for example, generate a sql query with the data received in r
}