gpt4 book ai didi

java - 我必须在哪里初始化类成员变量JavaFX

转载 作者:行者123 更新时间:2023-12-01 17:56:04 25 4
gpt4 key购买 nike

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

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 函数本身。

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

知道为什么吗?我必须在哪里初始化我的类成员变量?

编辑:

好吧,我尝试为我的 View 创建一个专用 Controller ,我的第一个问题似乎已经解决,一切都按预期初始化,但现在我的 ListView 每次添加 Contact 到我的列表,但以前就是这样。我不知道创建一个单独的 Controller 会破坏什么,你知道吗?

这是完整的代码

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>

最佳答案

在我看来,将负责启动应用程序并加载 .fxml 文件的类与您的 Controller 类混合在一起是不好的做法>,它关心控制你的 UI,例如,在你的情况下,你有 clickSendMessage() 方法,该方法必须位于 Controller 类中。

所以我建议您编写一个单独的类,即您的 Controller ,将 Controller 附加到 .fxml 文件,然后您可以更轻松地处理 UI 和逻辑部分之间的所有交互。我可以向您展示一个简单的例子:

package stackoverflow;

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="stackoverflow.TestController">
// here you can fill it with content
</AnchorPane>

现在你有了单独的 Controller 和 .fxml,这样你就可以像在主类中一样加载这个 .fxml 然后你可以在你的类中添加所有内容您想要控制您的应用程序(包括该方法)的 Controller 。这是构建 javafx 应用程序的一种非常简单明了的方法。我认为这是可以理解的,但如果我错过了什么,请随时问我。

关于java - 我必须在哪里初始化类成员变量JavaFX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44671365/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com