ublic class TheMedicalResourceManagementSystem
{
JFrame jf;
JPanel jp;
JButton b;
JTextField t;
JTextField t2;
public static void main(String[] args)
{
TheMedicalResourceManagementSystem cc = new TheMedicalResourceManagementSystem();
// SwingUtilities.invokeLater(() -> new GUI("The Medical Resource Management System").setVisible(true));
}
public TheMedicalResourceManagementSystem()
{
jf = new JFrame("Frame");
jp = new JPanel();
jp.setLayout(new FlowLayout());
jf.add(jp);
t = new JTextField(15);
jp.add(t);
t2 = new JTextField(15);
jp.add(t);
jp.add(t2);
b= new JButton("Login");
jp.add(b);
jf.setSize(200,200);
jf.setVisible(true);
String username = t.getText();
String password = t2.getText();
b.addActionListener((ActionEvent e) -> {
if(username.equals("admin") && password.equals("password"))
{
SwingUtilities.invokeLater(() -> new GUI("Medical Remote Management System").setVisible(true));
}
else
{
JOptionPane.showMessageDialog( null, "Incorrect username or password , Please try again");
}});
}
}
在我的程序中,我希望输入用户名和密码,当输入并正确时,它应该运行所有内容。我无法让它运行,因为当我输入管理员和密码时,它一直告诉我用户或密码错误,即使它不是?
最佳答案
像大多数 GUI 框架一样,Swing 是事件驱动的。这意味着信息与其收集时间相关。
在上面的示例中,您甚至在 UI 完全实现(呈现给用户)之前就获取了用户名
和密码
,因此它只会返回初始值文本字段的值(可能为空)
相反,您需要在 ActionEvent
发生时获取用户名
和密码
,因为此时它与代码最相关,例如...
b.addActionListener((ActionEvent e) -> {
String username = t.getText();
String password = t2.getText();
if(username.equals("admin") && password.equals("password")) {
SwingUtilities.invokeLater(() -> new GUI("Medical Remote Management System").setVisible(true));
} else {
JOptionPane.showMessageDialog( null, "Incorrect username or password , Please try again");
}
});
关于java - JTextField 和 JButton 登录页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47641926/