首页 > 解决方案 > 覆盖中的 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");
        }
    }
}

标签: javaswinguser-interfaceserverchat

解决方案


我建议您检查一下并使用 (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
        
    }

推荐阅读