我试图在我的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的String值