简体   繁体   English

JavaFX TableView与SceneBuilder

[英]JavaFX TableView With SceneBuilder

I have a really simple class that takes a list of jobs and attempts to populate a TableView with them. 我有一个非常简单的类,它接收作业列表并尝试用它们填充TableView。 I have this working without using FXML, but I am now trying new methods. 我可以在不使用FXML的情况下进行此工作,但是现在我正在尝试新的方法。 The issue I have is that; 我的问题是;

tView.getItems().addAll(jobList);

returns a null pointer, however if I create a new TableView there is no data in the table at all. 返回一个空指针,但是,如果我创建一个新的TableView,表中根本没有数据。

I believe that where I am going wrong is the use of the TableView that is constructed in SceneBuilderand not correctly initialising it, however I am confused in how I would do this. 我相信我要出问题的地方是使用SceneBuilder中构造的TableView并没有正确初始化它,但是我对如何执行此操作感到困惑。 Here is my InterFace method class; 这是我的InterFace方法类;

public class InterfaceMethods {

    @FXML TableView<Job> tView;

    @SuppressWarnings("unchecked")
    public void populateTableView(Connection connection, Stage stage) throws Exception {

        Parent root;
        root = FXMLLoader.load(getClass().getResource("TableViewInterface.fxml"));
        Scene scene = new Scene(root);
        stage.setScene(scene);

        JobDataAccessor jobAccessor = new JobDataAccessor();
        final String query = "SELECT * FROM progdb.adamJobs";
        List<Job> jobList = jobAccessor.getJobList(connection, query);
        //System.out.println(query);
        //System.out.println(connection);
        tView.getItems().addAll(jobList);
    }
}

Here is my MainApp class; 这是我的MainApp类;

public class MainApp extends Application {

private CheckUserDetails checkDetails;
private String pString, username = System.getProperty("user.name");
private InterfaceMethods iMethods;
private Connection connection;
@FXML private Button submitButton;
@FXML private PasswordField passField;
@FXML private Label warnLabel;

@Override
public void start(Stage stage) throws Exception {
    Parent root = FXMLLoader.load(getClass().getResource("MainInterface.fxml"));
    Scene scene = new Scene(root);
    stage.setScene(scene);
    stage.show();
}

@FXML
private void loginCheck() throws Exception {
    checkDetails = new CheckUserDetails();
    pString = new String();
    pString = passField.getText();
    System.out.println(pString);
    if (checkDetails.checkUserDetails(pString, username) != null) {
        setConnection(checkDetails.connection);
        handleTableView();
    } else {
        warnLabel.setVisible(true);
    }
}

@FXML
public void handleTableView() throws Exception {
    iMethods = new InterfaceMethods();

    Stage stage = (Stage) submitButton.getScene().getWindow();  

    connection = getConnection();

    iMethods.populateTableView(connection, stage);
}

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

Finally here is one of my two FXML files, the one with the TableView within it; 最后,这是我的两个FXML文件之一,其中一个包含TableView。

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

<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.GridPane?>

<AnchorPane 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="application.InterfaceMethods">
   <children>
      <TableView fx:id="tView" layoutX="17.0" layoutY="19.0" prefHeight="347.0" prefWidth="570.0">
        <columns>
          <TableColumn prefWidth="75.0" text="CaseNO." />
          <TableColumn prefWidth="75.0" text="Case Notes" />
            <TableColumn prefWidth="75.0" text="Date Created" />
            <TableColumn prefWidth="75.0" text="Deadline" />
            <TableColumn prefWidth="75.0" text="Priority" />
            <TableColumn prefWidth="75.0" text="Completed" />
        </columns>
         <columnResizePolicy>
            <TableView fx:constant="CONSTRAINED_RESIZE_POLICY" />
         </columnResizePolicy>
      </TableView>
   </children>
</AnchorPane>

The getJobList method (inside a different class); getJobList方法(在另一个类中);

    public List<Job> getJobList(final Connection connection, final String query) throws SQLException {
    try (Statement stmnt = connection.createStatement(); ResultSet rs = stmnt.executeQuery(query);) {
        jobList = new ArrayList<>();
        System.out.println(connection);
        System.out.println(query);
        while (rs.next()) {
            caseNumber = rs.getString("CaseNO");
            caseNotes = rs.getString("CaseNotes");
            dateCreated = rs.getString("DateCreated");
            deadlineDate = rs.getString("Deadline");
            prioritySetting = rs.getInt("Priority");
            completedSetting = rs.getString("Completed");
            job = new Job(caseNumber, caseNotes, dateCreated, deadlineDate, prioritySetting, completedSetting);
            jobList.add(job);
        }
        return jobList;
    }
}

You need to define the controller for your FXML. 您需要为FXML定义控制器。

For example your portion of FXML is:- 例如,您的FXML部分是:

<AnchorPane id="AnchorPane" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="288.0" prefWidth="293.0" xmlns:fx="http://javafx.com/fxml">
<children>
    <TableView fx:id="tableView" layoutX="35.0" layoutY="28.0" prefHeight="200.0" prefWidth="227.0">
    <columns>
        <!-- Columns for table view-->
    </columns>
    </TableView>
</children>
</AnchorPane>

1) Create a controller for your FXML page like:- 1)为您的FXML页面创建一个控制器,例如:

 fx:controller="com.code.Controller"

2) Now in your Controller, you can do like:- 2)现在,在您的控制器中,您可以执行以下操作:

package com.code;

    public class Controller implements Initializable {

        @FXML private TableView<User> tableView;

All @FXML annotated fields of controller class are instantiated by the FXMLLoader while loading the fxml file having the fx:controller equal to that controller class or the class you set by fxmlLoader.setController(). 控制器类的所有@FXML注释字段都由FXMLLoader实例化,同时加载具有与该控制器类或您通过fxmlLoader.setController()设置的类相等的fx:controller的fxml文件。 If you instantiate the controller class yourself these @FXML annotated fields will be null. 如果您自己实例化控制器类,则这些@FXML注释字段将为null。 So here sample approach for using setController() instead of fx:controller in fxml file: 因此,这里是在fxml文件中使用setController()代替fx:controller的示例方法:

MainApp 主程序

public class MainApp extends Application
{
    @Override
    public void start( Stage stage ) throws Exception
    {
        MainController mainController = new MainController(getConnection());

        Scene scene = new Scene( mainController.getLayout() );

        stage.setScene( scene );
        stage.show();
    }


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

MainController 主控制器

public class MainController implements Initializable
{

    @FXML
    private Label label;

    private Parent layout;

    private Connection connection;


    public MainController(Connection connection)
    {
        this.connection = connection;

        FXMLLoader fxmlLoader = new FXMLLoader( getClass().getResource( "Main.fxml" ) );
        fxmlLoader.setController( this );
        try
        {
            layout = ( Parent ) fxmlLoader.load();
        }
        catch ( IOException exception )
        {
            throw new RuntimeException( exception );
        }
    }


    public Parent getLayout()
    {
        return layout;
    }


    @FXML
    private void handleTableView( ActionEvent event )
    {
        InterfaceMethods iMethods = new InterfaceMethods( connection );
        label.getScene().setRoot(iMethods.getLayout());
        label.getScene().getWindow().sizeToScene();
    }


    @Override
    public void initialize( URL url, ResourceBundle rb )
    {
        // do work with @FXML annotated fields in here
        label.setText( "Initial data!");
    }

}

Main.fxml Main.fxml

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

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

<AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320" xmlns:fx="http://javafx.com/fxml/1">
    <children>
        <Button layoutX="126" layoutY="90" text="Click Me!" onAction="#handleTableView" fx:id="button" />
        <Label layoutX="126" layoutY="120" minHeight="16" minWidth="69" fx:id="label" />
    </children>
</AnchorPane>

InterfaceMethods 接口方法

public class InterfaceMethods implements Initializable
{

    @FXML
    TableView<Job> tView;

    private Parent layout;

    private Connection connection;


    public MainController( Connection connection )
    {
        this.connection = connection;

        FXMLLoader fxmlLoader = new FXMLLoader( getClass().getResource( "TableViewInterface.fxml" ) );
        fxmlLoader.setController( this );
        try
        {
            layout = ( Parent ) fxmlLoader.load();
        }
        catch ( IOException exception )
        {
            throw new RuntimeException( exception );
        }
    }


    public Parent getLayout()
    {
        return layout;
    }

    @Override
    public void initialize( URL url, ResourceBundle rb )
    {
        // do work with @FXML annotated fields in here
        tView.setItems(...);
    }

}

Note that Main.fxml and TableViewInterface.fxml do not have fx:controller in it. 请注意,Main.fxml和TableViewInterface.fxml中没有fx:controller

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM