【发布时间】:2021-03-15 02:32:43
【问题描述】:
我希望“登录”按钮关闭符号框架并打开一个新的JFrame。但在我着手让按钮打开另一个JFrame 之前,我想看看该按钮是否可以关闭当前打开的框架。我是 Java 新手,这是我正在从事的第一个项目。
我已经尝试了我所知道的一切,但仍然无法正常工作。
这里有一些代码:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
class digit implements ActionListener {
private static JLabel userLabel;
private static JTextField userText;
private static JLabel passLabel;
private static JPasswordField passText;
private static JButton button;
private static JLabel success;
public static void main(String args[]){
JPanel panel = new JPanel();
JFrame frame = new JFrame("Login");
frame.setSize(300, 170);
Image icon = Toolkit.getDefaultToolkit().getImage("appicon.png");
frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
frame.add(panel);
frame.setIconImage(icon);
panel.setLayout(null);
userLabel = new JLabel("Username");
userLabel.setBounds(10, 20, 80, 25);
panel.add(userLabel);
userText = new JTextField();
userText.setBounds(100, 20, 165, 25);
panel.add(userText);
passLabel = new JLabel("Password");
passLabel.setBounds(10, 50, 80, 25);
panel.add(passLabel);
passText = new JPasswordField();
passText.setBounds(100, 50, 165, 25);
panel.add(passText);
button = new JButton("Login");
button.setBounds(10, 80, 80, 25);
button.addActionListener(new digit());
panel.add(button);
success = new JLabel();
success.setBounds(10, 110, 300, 25);
panel.add(success);
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e){
String username = userText.getText();
String password = passText.getText();
if(username.equals("The8th") && password.equals("Password123")) {
success.setText("Login Successful!");
frame.dispose();
} else {
success.setText("Invalid Username Or Password");
}
}
}
【问题讨论】:
-
您的代码的整个结构是错误的:1) 类名以大写变量开头,2) 不使用静态变量 3) 仅在 main() 方法中创建框架。所有其他组件都应该在您的“数字”类中创建。 4) 不要使用空布局和 setBounds()。 Swing 旨在与布局管理器一起使用。阅读 How to Use Text Fields 上的 Swing 教程部分。 “TextDemo”将向您展示如何更好地构建您的代码。
-
然后在你的 ActionListener 中。您可以使用
SwingUtilities.windowForComponent(...)方法访问按钮已添加到的框架。 ActionEvent 包含事件的“源”对象,在本例中是被点击的按钮。 -
"open a new JFrame" 登录应该是模态的
JDialog。见The Use of Multiple JFrames, Good/Bad Practice?
标签: java swing user-interface server chat