我必须在哪里初始化 class 成员变量 JavaFX

Where do I have to initialize class member variables JavaFX

我正在通过 Java 中的场景生成器使用 JavaFX 和 JFoenix 制作一个应用程序,但是我在 class 成员变量的初始化方面遇到了一些问题。这是我的代码

public class MessageApp extends Application {

    private AnchorPane mainLayout;
    private Stage primaryStage;
    private int i = 5;

    public void init() {
        i = 0;
    }

    public void start(Stage primaryStage) {
        try {
            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(PeerApp.class.getResource("PeerApp.fxml"));
            mainLayout = loader.load();
        } catch (IOException e) {
            e.printStackTrace();
        }

        this.primaryStage = primaryStage;
        this.primaryStage.setTitle("Test");
        JFXDecorator decorator = new JFXDecorator(primaryStage, mainLayout);
        decorator.setCustomMaximize(true);
        Scene scene = new Scene(decorator, 600, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    @FXML
    private void clickSendMessage() {
        System.out.println("i = " + i);
    }

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

这里的问题是,即使我在 init 函数或 start 函数中将 I 重置为 0,当我单击触发 clickSendMessage 函数的发送按钮时,我的 println 打印 "i = 5"。重置它的唯一方法是将 i = 0 放入 clickSendMessage 函数本身。

所以,在这种情况下,这不是一个大问题,但是如果我在声明期间不初始化一个 class 成员变量,即使我在 initstart 函数,当我点击我的发送按钮时我的应用程序崩溃了,因为在这个阶段它仍然被认为是 null 但我不知道为什么。

有什么原因的线索吗?我必须在哪里初始化我的 class 成员变量?

编辑:

好的,所以我尝试为我的视图创建一个专用控制器,我的第一个问题似乎已解决,一切都按预期初始化但现在我的 ListView 每次添加 [= 时都不会更新23=] 到我的列表,但以前是这种情况。我不知道我通过创建一个单独的控制器破坏了什么,知道吗?

这是完整的代码

PeerApp.java

public class PeerApp extends Application {

    private AnchorPane mainLayout;
    private Stage primaryStage;

    public void start(Stage primaryStage) {
        try {
            FXMLLoader loader = new FXMLLoader();
            loader.setLocation(PeerApp.class.getResource("PeerApp.fxml"));
            mainLayout = loader.load();
        } catch (IOException e) {
            e.printStackTrace();
        }

        this.primaryStage = primaryStage;
        this.primaryStage.setTitle("Peer Messenger");
        JFXDecorator decorator = new JFXDecorator(primaryStage, mainLayout);
        decorator.setCustomMaximize(true);
        Scene scene = new Scene(decorator, 600, 400);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

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

PeerAppController.java

public class PeerAppController {

    private PeerApplication peer = new PeerApplication("1234");
    private ObservableList<Contact> contacts;
    private ChangeListener<Contact> listener;
    private int i = 5;

    @FXML
    private JFXListView<Contact> contactList;
    @FXML
    private JFXButton addContactButton;
    @FXML
    private JFXTextArea messageTextArea;
    @FXML
    private GridPane chatGridPane;
    @FXML
    private JFXButton sendButton;

    @FXML
    public void initialize() {
        initPeer();
        initRootLayout();
        contacts = FXCollections.observableArrayList(Contact.extractor());

        contactList.setItems(contacts);

        listener = new ChangeListener<Contact>() {
            @Override
            public void changed(ObservableValue<? extends Contact> observable, Contact oldValue, Contact newValue) {
                chatGridPane.getChildren().clear();
                List<Message> conversation = contacts.get(contactList.getSelectionModel().getSelectedIndex()).getConversation();
                int i;

                i = 0;
                while (conversation.size() >= i + 1) {
                    Label messageLabel = new Label(conversation.get(i).getContent());
                    chatGridPane.addRow(i, messageLabel);
                    i++;
                }
            }
        };
        contactList.getSelectionModel().selectedItemProperty().addListener(listener);

        i = 0;
    }

    private void initPeer() {
        peer.init(EncryptionType.NONE, CompressionType.NONE);
        peer.getPeerDaemonPlug().setComListener(new ICommunicationListener() {
            @Override
            public void onDataReceived(String s) {
                Label labelMessage = new Label(s);
                GridPane.setHalignment(labelMessage, HPos.RIGHT);
                chatGridPane.addRow(getRowCount(chatGridPane) + 1, labelMessage);
                contacts.get(contactList.getSelectionModel().getSelectedIndex()).getConversation().add(new Message(s, false));
            }

            @Override
            public void onStreamPacketCompleted(OutputStream outputStream) {
            }
        });
    }

    private void initRootLayout() {
        // Init the layout
        ColumnConstraints c1 = new ColumnConstraints();
        c1.setPercentWidth(100);

        sendButton = new JFXButton();
        contactList = new JFXListView<Contact>();
        chatGridPane = new GridPane();
        chatGridPane.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
        chatGridPane.getColumnConstraints().add(c1);
    }

    @FXML
    private void clickAddContact() {
        TextInputDialog dialog = new TextInputDialog("");
        dialog.setTitle("New Contact");
        dialog.setHeaderText("Add a new contact");
        dialog.setContentText("Enter the ID of your contact:");

        Optional<String> result = dialog.showAndWait();
        result.ifPresent(id -> {
            Contact c = new Contact(id);
            contacts.add(c);
            System.out.println(contactList.getItems().size());
        });
    }

    @FXML
    private void clickSendMessage() {
        // Not to be there

        String message = messageTextArea.getText();
        Label labelMessage = new Label(message);

        try {
            peer.sendRequest(sendDataToNode, new SendDataToNodeParam(contactList.getSelectionModel().getSelectedItem().toString(), message));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            i = 0;
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            i = 1;
            e.printStackTrace();
        } catch (InvalidAlgorithmParameterException e) {
            i = 2;
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            i = 3;
            e.printStackTrace();
        } catch (BadPaddingException e) {
            i = 4;
            e.printStackTrace();
        } catch (IOException e) {
            i = 5;
            e.printStackTrace();
        }

        messageTextArea.setText("");
        GridPane.setHalignment(labelMessage, HPos.LEFT);
        chatGridPane.addRow(getRowCount(chatGridPane) + 1, labelMessage);
        contacts.get(contactList.getSelectionModel().getSelectedIndex()).getConversation().add(new Message(message, true));
        System.out.println("i = " + i);
    }

    private int getRowCount(GridPane pane) {
        int numRows = pane.getRowConstraints().size();
        for (int i = 0; i < pane.getChildren().size(); i++) {
            Node child = pane.getChildren().get(i);
            if (child.isManaged()) {
                Integer rowIndex = GridPane.getRowIndex(child);
                if(rowIndex != null){
                    numRows = Math.max(numRows,rowIndex+1);
                }
            }
        }
        return numRows;
    }

}

Contact.java

public class Contact {
    private StringProperty id;
    private List<Message> conversation;

    public Contact(String id) {
        this.id = new SimpleStringProperty(id);
        this.conversation = FXCollections.observableArrayList();
    }

    public static Callback<Contact, Observable[]> extractor() {
        return new Callback<Contact, Observable[]>() {
            @Override
            public Observable[] call(Contact param) {
                return new Observable[]{param.id};
            }
        };
    }

    @Override
    public String toString() {
        return String.format("%s", id.get());
    }

    public StringProperty getId() {
        return this.id;
    }

    public void setId(StringProperty id) {
        this.id = id;
    }

    public List<Message> getConversation() {
        return this.conversation;
    }
}

PeerApp.fxml

<AnchorPane prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1" fx:controller="PeerAppController">
    <children>
        <SplitPane dividerPositions="0.29797979797979796" layoutX="200.0" layoutY="120.0" prefHeight="400.0" prefWidth="600.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
            <items>
                <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
                    <children>
                  <JFXListView fx:id="contactList" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0" />
                        <JFXButton fx:id="addContactButton" buttonType="RAISED" layoutX="133.0" layoutY="357.0" onAction="#clickAddContact" ripplerFill="#10ae07" text="+" textAlignment="CENTER" AnchorPane.bottomAnchor="14.0" AnchorPane.rightAnchor="14.0" />
                    </children>
                </AnchorPane>
                <AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="160.0" prefWidth="100.0">
                    <children>
                        <JFXTextArea fx:id="messageTextArea" focusColor="#40a85c" layoutX="15.0" layoutY="237.0" maxHeight="50.0" minHeight="10.0" prefHeight="50.0" prefWidth="339.0" AnchorPane.bottomAnchor="10.0" AnchorPane.leftAnchor="5.0" AnchorPane.rightAnchor="72.0" />
                        <ScrollPane layoutX="12.0" layoutY="12.0" prefHeight="276.0" prefWidth="394.0" AnchorPane.bottomAnchor="65.0" AnchorPane.leftAnchor="5.0" AnchorPane.rightAnchor="5.0" AnchorPane.topAnchor="5.0">
                     <content>
                        <GridPane fx:id="chatGridPane" maxHeight="1.7976931348623157E308" maxWidth="1.7976931348623157E308">
                          <columnConstraints>
                            <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                            <ColumnConstraints hgrow="SOMETIMES" minWidth="10.0" prefWidth="100.0" />
                          </columnConstraints>
                          <rowConstraints>
                            <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                            <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                            <RowConstraints minHeight="10.0" prefHeight="30.0" vgrow="SOMETIMES" />
                          </rowConstraints>
                        </GridPane>
                     </content></ScrollPane>
                  <JFXButton fx:id="sendButton" layoutX="350.0" layoutY="338.0" onAction="#clickSendMessage" prefHeight="50.0" prefWidth="64.0" ripplerFill="#18cd00" text="SEND" textAlignment="CENTER" textFill="#0dae04" AnchorPane.bottomAnchor="5.0" AnchorPane.leftAnchor="344.0" AnchorPane.rightAnchor="5.0" />
                    </children>
                </AnchorPane>
            </items>
        </SplitPane>
    </children>
</AnchorPane>

朋友,你也把你的PeerApp.fxml控制器设置为MessageApp了吗?

否则,当您点击发送按钮时,它不会触发clickSendMessage()。

但是如果您将 PeerApp.fxml 的控制器设置为 MessageApp,javafx 会自动创建 MessageApp 的另一个实例,因此如果您单击发送按钮,它实际上会触发 MessageApp 的 clickSendMessage() 的另一个实例,并打印它的第一个变量。

或者你能post你的PeerApp.fxml代码方便我们查吗?

init() 方法是从应用程序 class 覆盖的,它会在我们启动 javafx 应用程序时自动 运行。

在我看来,将负责启动您的应用程序并加载您的 .fxml 文件的 class 与您的 class 混合使用是不好的做法=13=],它关心控制你的 UI,例如在你的情况下你有 clickSendMessage() 方法必须在控制器 class.

所以我建议你写一个单独的 class 作为你的 Controller ,你将你的控制器附加到 .fxml 文件然后你可以更容易地处理 UI 之间的所有交互和逻辑部分。我可以给你看一个简单的例子:

package Whosebug;

import javafx.fxml.Initializable;

import java.net.URL;
import java.util.ResourceBundle;

public class TestController implements Initializable {

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        // here are  all stuffs initialized
    }
}

那么 .fxml 文件如下所示:

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

<?import javafx.scene.layout.AnchorPane?>
<AnchorPane prefHeight="500.0" prefWidth="700.0" xmlns="http://javafx.com/javafx/8.0.91" xmlns:fx="http://javafx.com/fxml/1" 
fx:controller="Whosebug.TestController">
// here you can fill it with content
</AnchorPane>

所以现在你有一个单独的控制器和一个 .fxml 所以你可以加载这个 .fxml 就像你在主 class 中所做的那样然后你可以在你的控制器中添加所有东西你想控制你的应用程序,包括那个方法。这是构建 javafx 应用程序的一种非常简单明了的方法。 我认为这是可以理解的,但如果我遗漏了什么,请随时问我。