我尝试在 Java FX 程序中使用 if/else 语句,但即使满足“if”语句,它也会不断向我提供“else”输出。我检查了我的 onaction 事件和我的 fx id,以确保它们是对应的。
package sample;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
public class Controller {
@FXML
private Label user;
@FXML
private Label pass;
@FXML
public Button button;
@FXML
public TextField username;
@FXML
public TextField password;
@FXML
public void doSomething(){
if ((username.equals("John")) && (password.equals("Doe"))) {
System.out.println("Welcome");
} else{
System.out.println("Please Try again");
}
}
}
<?import javafx.scene.layout.GridPane?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<GridPane fx:controller="sample.Controller"
xmlns:fx="http://javafx.com/fxml" alignment="center" hgap="20" vgap="10">
<Label text="Username" GridPane.columnIndex="0" GridPane.rowIndex="0" fx:id="user"/><TextField GridPane.columnIndex="0" GridPane.rowIndex="1" fx:id="username"/>
<Label text="Password" GridPane.columnIndex="1" GridPane.rowIndex="0" fx:id="pass"/><TextField GridPane.columnIndex="1" GridPane.rowIndex="1" fx:id="password"/>
<Button text="Login" GridPane.columnIndex="2" GridPane.rowIndex="1" GridPane.columnSpan="2" fx:id="button" onAction="#doSomething"/>
</GridPane>
最佳答案
使用username.equals()
和password.equals()
代替
username.getText().equals()
和 password.getText().equals()
这将给出 TextArea 的字符串值
关于java - 在 JavaFX 中使用 If/Else 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41906165/