gpt4 book ai didi

JavaFX TextArea字符串读取问题

转载 作者:行者123 更新时间:2023-12-01 18:37:00 25 4
gpt4 key购买 nike

我正在尝试在 JavaFX 中创建一个登录系统,我需要检查以便与电子邮件对应的 textArea 的字符串与我的 User 类中的电子邮件变量相同。但是,我用于将 textArea 中的字符串与用户详细信息进行比较的方法将始终返回 false。我不知道为什么。我尝试过 .equals()、.compareTo、甚至 .charAt() 并用 1 个字母对其进行测试,但它仍然会返回 false。

这是我的方法代码。请注意,这是我用于将 textArea 中的字符串与 User.getEmail 中的字符串进行比较的方法。

public boolean checkCredentials()
{
return text1.getText().equals(user.getEmail());
}

这是我的 User 类中的方法 .getEmail() 的代码:

private String email = "1";
public String getEmail()
{
return email;
}

此外,即使在 textArea 中的输入为“1”、用户类中的字符串 Email 为“1”的情况下运行,我仍然得到返回 false:

public boolean checkCredentials()
{
return text1.getText().length() == user.getEmail().length();
}

我的猜测是,textArea 中的字符串在某个地方比 User 类中的字符串有“额外”的东西。我尝试打印出两个字符串的长度,但得到了相同的答案。

重新创建所需的最少代码,注意必须安装 JavaFX,并且必须使用 JavaFX 应用程序模板:

import javafx.application.Application;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application
{

Stage window;
Scene scene1;

String sEmail;

// TextBoxes Dec.
TextArea text1 = new TextArea();

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

public boolean checkCredentials()
{
return text1.getText().equals(sEmail);
}

@Override
public void start(Stage primaryStage)
{
window = primaryStage;

sEmail = "1";

// TextBoxes Ini.
text1.setMaxWidth(200);
text1.setMaxHeight(25);
text1.setMinHeight(25);

// Button
Button button1 = new Button("Check string");
if(checkCredentials())
{
button1.setOnAction(e -> System.out.println("The email is correct"));
}
else
{
button1.setOnAction(e -> System.out.println("The email is NOT correct"));
}

// Layout1
VBox layout1 = new VBox(20);
layout1.setAlignment(Pos.CENTER);
layout1.getChildren().add(text1, button1);
scene1 = new Scene(layout1, 750, 500);

window.setScene(scene1);
window.setTitle("Hello");
window.show();
}

}

最佳答案

上面发布的当前方法将始终返回 false,除非比较的字符串为空。这是因为检查是在程序运行时进行的,这意味着程序开始时的 textArea 中始终没有任何内容。

要解决此问题,请为按钮创建一个事件处理程序,如下所示:

button1.setOnAction(new EventHandler<ActionEvent>()
{
@Override
public void handle(ActionEvent event)
{
if(text1.getText().equals(user.getEmail()))
{
window.setScene(scene2);
}
else
{
AlertBox.display("ALERT!", "Please provide correct details");
}
}
});

此方法会在按下按钮时比较字符串,如果它们相同,则转到 scene2。

P.S AlertBox 是我与 display() 一起制作的一个类。

关于JavaFX TextArea字符串读取问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60013463/

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