java - 覆盖中的 ActionEvent 找不到 JFrame
问题描述
我希望“登录”按钮关闭符号框架并打开一个新的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");
}
}
}
解决方案
我建议您检查一下并使用 (e.getSource()) 而不是添加更多按钮,而且您的整个代码似乎错误 https://docs.oracle.com/javase/tutorial/uiswing /events/actionlistener.html
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == button ) {
//write your executable code here
}
else if (e.getSource() == anotherbutton){
//write your executable code here
}
推荐阅读
- javascript - 为什么当远程调试未激活时,我的用户为空,而当它激活时,它是一个对象?
- css - 为什么这个 CSS 选择器不起作用?.card > .card-header ~ *:not(:card-body)
- android - 安装 android 应用程序时的权限对话框
- java - 在 Maven 模块项目中集成
- r - R:为即将推出的 ggplot2 版本 2.3.0 更新我的包
- wordpress - 如何删除仪表板中的wordpress文档菜单链接
- apache-kafka - Flink kafka 连接器 0.11.0
- groovy - Magnolia 安排一个 Groovy 脚本
- css - 将 '.col-*-*' 类直接放在 Bootstrap 3 中的元素上是否被认为是不好的做法?
- r - R 中的文本分析(使用印地语字符创建词云)