java - 无法让项目显示在文本字段中

标签 java mysql

尝试编写一些代码,当我在表格 View 中选择一行时,该代码会自动使其显示在我添加新数据部分中的文本字段框中。我设置了 fxml,它与我的场景生成器交互。

我现在很确定问题出在这行代码上。 userNameBox 即将为空。

userNameBox.setText(staff.getuserName());

Controller 代码

public class StaffController implements Initializable {

    Connection conn;
    ResultSet rs;
    @FXML
    private Label label;
    @FXML
    private TableView<Retailer> tableUser;
    @FXML
    private TableColumn<Retailer, String> columnuserName;
    @FXML
    private TableColumn<Retailer, String> columnfirstName;
    @FXML
    private TableColumn<Retailer, String> columnlastName;
    @FXML
    private TableColumn<Retailer, String> columnuserEmail;
    @FXML
    private TableColumn<Retailer, Integer> columnSalary;
    @FXML
    private Button btnLoad;
    @FXML
    private Button addButton;
    @FXML
    private TextField userNameBox;
    @FXML
    private TextField firstNameBox;
    @FXML
    private TextField lastNameBox;
    @FXML
    private TextField emailBox;
    @FXML
    private TextField salaryBox;
    // Initialize observable list to hold out database data
    private ObservableList<Retailer> data;
    private Database dc;

    private PreparedStatement query;
    Connection c;

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
        dc = new Database();



    }

    @FXML
            public void showOnClick(){

                dc = new Database();
                c = dc.Connect();



                try{

                    Retailer staff=(Retailer)tableUser.getSelectionModel().getSelectedItem();
                    String querySelect="SELECT * from Staff";
                    System.out.println(querySelect);
                    System.out.println(query);
                    System.out.println(c);
                    System.out.println(staff);
                    query=c.prepareStatement(querySelect);

                    userNameBox.setText(staff.getuserName());
                    firstNameBox.setText(staff.getfirstName());
                    lastNameBox.setText(staff.getlastName());
                    emailBox.setText(staff.getuserEmail());
                    salaryBox.setText(Integer.toString(staff.getSalary()));

                query.close();
                rs.close();

                }
                catch(SQLException e){

                    System.out.println("SQL wrong");
                }


            }

FXML 代码

<AnchorPane id="AnchorPane" prefHeight="500.0" prefWidth="616.0" xmlns="http://javafx.com/javafx/8.0.111" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.StaffController">
    <children>
        <Label fx:id="label" layoutX="126" layoutY="120" minHeight="16" minWidth="69" />
      <TableView fx:id="tableUser" layoutX="223.0" layoutY="74.0" onMouseClicked="#showOnClick" prefHeight="248.0" prefWidth="379.0">
        <columns>
          <TableColumn fx:id="columnuserName" prefWidth="75.0" text="User Name" />
          <TableColumn fx:id="columnfirstName" prefWidth="75.0" text="First Name" />
            <TableColumn fx:id="columnlastName" prefWidth="75.0" text="Last Name" />
            <TableColumn fx:id="columnuserEmail" prefWidth="90.0" text="Email" />
            <TableColumn fx:id="columnSalary" prefWidth="75.0" text="Salary" />
        </columns>
      </TableView>
      <Label layoutX="239.0" layoutY="31.0" prefHeight="27.0" prefWidth="138.0" text="Staff">
         <font>
            <Font size="18.0" />
         </font>
      </Label>
      <Button fx:id="btnLoad" layoutX="442.0" layoutY="347.0" mnemonicParsing="false" onAction="#loadDataFromDatabase" prefHeight="25.0" prefWidth="145.0" text="LOAD DETAILS" />
      <TextField id="userNameBox" layoutX="73.0" layoutY="95.0" prefHeight="25.0" prefWidth="112.0" promptText="User Name" />
      <TextField id="firstNameBox" layoutX="73.0" layoutY="137.0" prefHeight="25.0" prefWidth="112.0" promptText="First Name" />
      <TextField id="lastNameBox" layoutX="73.0" layoutY="179.0" prefHeight="25.0" prefWidth="112.0" promptText="Last Name" />
      <TextField id="emailBox" layoutX="70.0" layoutY="225.0" prefHeight="25.0" prefWidth="112.0" promptText="Email" />
      <TextField id="salaryBox" layoutX="73.0" layoutY="276.0" prefHeight="25.0" prefWidth="112.0" promptText="Salary" />
      <Button id="addButton" layoutX="161.0" layoutY="310.0" mnemonicParsing="false" onAction="#AddStaff" text="Add" />
      <Label layoutX="106.0" layoutY="58.0" text="Add new User" />
      <Label layoutX="14.0" layoutY="99.0" text="User Name" />
      <Label layoutX="14.0" layoutY="141.0" text="First Name" />
      <Label layoutX="14.0" layoutY="183.0" text="Last Name" />
      <Label layoutX="14.0" layoutY="229.0" text="Email" />
      <Label layoutX="14.0" layoutY="280.0" text="Salary" />
      <Circle id="deleteButton" fill="RED" layoutX="208.0" layoutY="116.0" radius="12.0" stroke="BLACK" strokeType="INSIDE" />
      <Rectangle id="deleteButton" arcHeight="5.0" arcWidth="5.0" fill="#f5f5f5" height="8.0" layoutX="202.0" layoutY="112.0" stroke="BLACK" strokeType="INSIDE" width="13.0" />
    </children>
</AnchorPane>

错误代码

Apr 30, 2017 6:52:55 PM javafx.fxml.FXMLLoader$ValueElement processValue
WARNING: Loading FXML document with JavaFX API of version 8.0.111 by JavaFX runtime of version 8.0.101
Sun Apr 30 18:53:04 BST 2017 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774)
    at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
    at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
    at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
    at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
    at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
    at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
    at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
    at javafx.event.Event.fireEvent(Event.java:198)
    at javafx.scene.Scene$ClickGenerator.postProcess(Scene.java:3470)
    at javafx.scene.Scene$ClickGenerator.access$8100(Scene.java:3398)
    at javafx.scene.Scene$MouseHandler.process(Scene.java:3766)
    at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
    at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
    at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:380)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:294)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:416)
    at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
    at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:415)
    at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
    at com.sun.glass.ui.View.notifyMouse(View.java:937)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at sun.reflect.misc.Trampoline.invoke(Unknown Source)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at sun.reflect.misc.MethodUtil.invoke(Unknown Source)
    at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1771)
    ... 31 more
Caused by: java.lang.NullPointerException
    at application.Retailer.<init>(Retailer.java:28)
    at application.StaffController.showOnClick(StaffController.java:100)
    ... 41 mor

e

最佳答案

看看这个 How to get clicked row ,遵循该代码和 tableview 上的 javafx 教程:

import javafx.application.Application;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.Stage;
import javafx.scene.control.TableRow;
import javafx.scene.input.MouseButton;


public class textRow extends Application {

    private TableView<Person> table = new TableView<Person>();
    private final ObservableList<Person> data =
        FXCollections.observableArrayList(
            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")
        );
    private final TextField rowData= new TextField();

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

    @Override
    public void start(Stage stage) {
        Scene scene = new Scene(new Group());
        stage.setTitle("Table View Sample");
        stage.setWidth(450);
        stage.setHeight(550);

        final Label label = new Label("Address Book");
        label.setFont(new Font("Arial", 20));

        table.setEditable(true);

        TableColumn firstNameCol = new TableColumn("First Name");
        firstNameCol.setMinWidth(100);
        firstNameCol.setCellValueFactory(
                new PropertyValueFactory<Person, String>("firstName"));

        TableColumn lastNameCol = new TableColumn("Last Name");
        lastNameCol.setMinWidth(100);
        lastNameCol.setCellValueFactory(
                new PropertyValueFactory<Person, String>("lastName"));

        TableColumn emailCol = new TableColumn("Email");
        emailCol.setMinWidth(200);
        emailCol.setCellValueFactory(
                new PropertyValueFactory<Person, String>("email"));

        table.setItems(data);
        table.getColumns().addAll(firstNameCol, lastNameCol, emailCol);


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

                Person clickedRow = row.getItem();
                rowData.setText(clickedRow.toString());
            }
        });
        return row ;
});

        final VBox vbox = new VBox();
        vbox.setSpacing(5);
        vbox.setPadding(new Insets(10, 0, 0, 10));
        vbox.getChildren().addAll(label, table, rowData);

        ((Group) scene.getRoot()).getChildren().addAll(vbox);

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

    public static class Person {

        private final SimpleStringProperty firstName;
        private final SimpleStringProperty lastName;
        private final SimpleStringProperty email;

        private Person(String fName, String lName, String email) {
            this.firstName = new SimpleStringProperty(fName);
            this.lastName = new SimpleStringProperty(lName);
            this.email = new SimpleStringProperty(email);
        }

        public String getFirstName() {
            return firstName.get();
        }

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

        public String getLastName() {
            return lastName.get();
        }

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

        public String getEmail() {
            return email.get();
        }

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

        public String toString(){
            return "Name: "+firstName.get()+" "+lastName.get()+ " Email: "+email.get();
        }
    }
} 

关于java - 无法让项目显示在文本字段中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43709592/

相关文章:

java - 通过java如何在不使用list()的情况下计算目录中的文件数

php - 有没有一种方法可以在不运行MAMP的情况下访问mysql数据库?

php - 两个mysql表之间和每个循环之间的关联数组

java - 我的 JDBC 连接池有什么问题?

java - 将 BigInteger 存储到 Mysql

mysql - 可以根据同一行中的其他值自动设置列中的值吗?

java - 错误 : swap(Object[], int,int) 在集合中具有私有(private)访问权限

java - spring mvc中不存在必需的MultipartFile参数 'file'

java - Eclipse PDT - 如何用于 Java 开发

java - DynamoDB 扫描查询和 BatchGet