【问题标题】:how to close a frame when button clicks单击按钮时如何关闭框架
【发布时间】:2011-05-30 07:33:36
【问题描述】:

我是 Java Swing 的新手。我正在创建一个包含一些组件的框架。

单击按钮时,我必须关闭框架并打开另一个框架。我试过setVisible(false),但它只隐藏框架,而不是关闭它。当我使用System.exit(0) 时,它关闭了所有框架。

我曾尝试过另一种方式,即将所有组件添加到面板中,然后首先添加面板。当框架必须关闭时,我只需删除 actionListener 中的那些组件并为相应的下一个进程添加其他组件。

我的整个代码如下:

package JavaApp;

import java.awt.Component;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.IllegalBlockSizeException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;


public class Login extends JFrame {

    public static JLabel labelUser;
    public static JLabel labelPass;
    public static JTextField textFieldUser;
    public static JPasswordField passwordField;
    public static JButton clear;
    public static JButton buttonLogin;
    public static JButton ChangePassword;
    public static JButton MasterKey;
    public static JButton AppKey;
    public static JPanel panelGnereate;
    public static JPanel panelLogin;
    public static JFrame frame;
    public static JLabel UserName;
    public static JTextField UserTxt;
    public static JButton GenerateKey;
    public static JPanel panelMaster;

    private static void designUI() {

        frame = new JFrame("Instalation");

        frame.setLayout(new GridLayout(2, 1));

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        panelLogin = new JPanel();
        panelLogin.setLayout(null);
        labelUser = new JLabel("Enter UserName");
        textFieldUser = new JTextField(10);
        labelPass = new JLabel("Enter Password");
        passwordField = new JPasswordField(10);
        buttonLogin = new JButton("Login");
        clear = new JButton("Cancel");
        panelLogin.add(buttonLogin);
        panelLogin.add(clear);
        panelLogin.add(labelUser);
        panelLogin.add(textFieldUser);
        panelLogin.add(labelPass);
        panelLogin.add(passwordField);
        textFieldUser.setBounds(200, 120, 100, 20);
        labelUser.setBounds(50, 120, 120, 20);
        labelPass.setBounds(50, 150, 120, 20);
        passwordField.setBounds(200, 150, 100, 20);
        buttonLogin.setBounds(70, 180, 100, 20);
        clear.setBounds(200, 180, 100, 20);
        buttonLogin.addActionListener(actionEvent);
        clear.addActionListener(actionEvent);
        frame.add(panelLogin);
        //Login frame ends...

        //Gnereate frame starts here..

        panelGnereate = new JPanel();
        panelGnereate.setLayout(null);
        ChangePassword = new JButton("Change Password");
        MasterKey = new JButton("Create Master Key");
        AppKey = new JButton("Create Application key");
        panelGnereate.add(ChangePassword);
        panelGnereate.add(MasterKey);
        panelGnereate.add(AppKey);
        ChangePassword.setBounds(150, 100, 200, 25);
        MasterKey.setBounds(150, 150, 200, 25);
        AppKey.setBounds(150, 200, 200, 25);

        ChangePassword.addActionListener(actionEvent);
        MasterKey.addActionListener(actionEvent);
        AppKey.addActionListener(actionEvent);
        //Gnerate Frame ends here..


        //MasterKey Generate Starts Here..

        panelMaster = new JPanel();
        panelMaster.setLayout(null);
        UserName = new JLabel("Text");
        UserTxt = new JTextField(20);
        GenerateKey = new JButton("Generate Key");
        panelMaster.add(UserName);
        panelMaster.add(UserTxt);
        panelMaster.add(GenerateKey);
        UserName.setBounds(150, 150, 50, 25);
        UserTxt.setBounds(220, 150, 100, 25);
        GenerateKey.setBounds(180, 180, 150, 25);
        GenerateKey.addActionListener(actionEvent);


        frame.setSize(500, 500);
        frame.setVisible(true);
    }


    public static void main(String args[]) {

         designUI();

    }
    private static ActionListener actionEvent = new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            String action = e.getActionCommand();
            if ("Login".equals(action)) {
                System.out.println("Login action" + e.getActionCommand());
                if ("".equals(textFieldUser.getText()) || "".equals(passwordField.getText())) {
                    JOptionPane.showMessageDialog(null,
                            "Enter Both UserName and Password");

                } else if ("admin".equals(textFieldUser.getText()) && "admin".equals(passwordField.getText())) {


                    System.out.println("login value" + textFieldUser.getText() + "     " + passwordField.getText());
                    frame.remove(panelLogin);
                    frame.add(panelGnereate);
                    frame.setVisible(true);
                } else {
                    JOptionPane.showMessageDialog(null,
                            "Wrong Password");

                }
            } else if ("Cancel".equals(action)) {
                System.out.println(e.getActionCommand());
                System.exit(0);

            } else if ("Change Password".equals(action)) {

            } else if ("Create Master Key".equals(action)) {
                frame.remove(panelGnereate);
               frame.add(panelMaster);

                frame.setVisible(true);
            } else if ("Create Application key".equals(action)) {
                System.out.println("Message " + UserTxt.getText());

                frame.setVisible(false);
            }else if("Generate Key".equals(action))
            {
                try {
                    new GenerateTxt(UserTxt.getText());
                } catch (NoSuchAlgorithmException ex) {
                    Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IllegalBlockSizeException ex) {
                    Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
                }

                frame.remove(panelMaster);
                frame.add(panelGnereate);
                 frame.setVisible(true);
            }
        }
        ;

    };
}

它在整个过程中都不起作用。当我单击主键时,它会在单击genearteKey 后显示相关的文本框,它会显示相同的面板而不是前一个面板。但是当我将鼠标移到那里时,它会显示两个面板的组件。

【问题讨论】:

    标签: java swing


    【解决方案1】:

    您可以向框架/对话框发送关闭事件。像这样:

    WindowEvent winClosingEvent = new WindowEvent( targetFrame, WindowEvent.WINDOW_CLOSING );
    Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent( winClosingEvent );
    

    我有时会在我的框架/对话框中实现 close() 方法,如下所示:

    public void close() {
        WindowEvent winClosingEvent = new WindowEvent( this, WindowEvent.WINDOW_CLOSING );
        Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent( winClosingEvent );
    }
    

    希望对您有所帮助...

    【讨论】:

      【解决方案2】:

      看看你的代码,你可能需要这样的东西:

                  if(frame == null)
                      frame = new JFrame();
                  else {
                      //remove the previous JFrame
                      frame.setVisible(false);
                      frame.dispose();
                      //create a new one
                      frame = new JFrame();
                  }
      

      你必须把它放在 actionperformed 方法中,这样框架才能被移除.. 顺便说一句,根据良好的编程习惯,将您的类变量从公共更改为私有是一个 gd 的想法。

      编辑:回答“闪烁”问题。 您正在从事件线程外部访问 swing 组件。 swing 小部件通常不是线程安全的。因此,您需要修改您的主要方法:

      public static void main(String[] args) {
          javax.swing.SwingUtilities.invokeLater(new Runnable() {
              public void run() {
                  designUI();
              }
          });
      }
      

      另外,请参阅Swing component flickering when updated a lot 了解更多查询。

      【讨论】:

      • 感谢您的快速回复先生..它工作正常..我在这里有一个小问题,当创建新框架时框架正在闪烁或闪烁..我需要解决这个问题。 .请
      • 只有相同的代码先生..我只更新 ActionPerformed 作为 public void actionPerformed(ActionEvent e) { if ("admin".equals(textFieldUser.getText()) && "admin".equals(passwordField .getText())) { //new keyGenerate(); frame.setVisible(false); frame.dispose();框架=新的 JFrame(); frame.add(panelGnereate); frame.setSize(500,500); frame.setVisible(true); } 每次我处理框架并创建新框架先生..
      • 我想我知道解决方案。你的代码不是线程安全的。我更新了我的解决方案来回答这个问题。
      【解决方案3】:

      你试过在框架上调用 dispose() 吗?我想这可能就是你要找的。​​p>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-04-07
        • 2022-01-06
        • 1970-01-01
        • 2022-08-05
        相关资源
        最近更新 更多