Java swing应用程序,关闭一个窗口,单击按钮时打开另一个窗口 [英] Java swing application, close one window and open another when button is clicked

查看:3518
本文介绍了Java swing应用程序,关闭一个窗口,单击按钮时打开另一个窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个netbeans Java应用程序,应该在启动应用程序时显示一个JFrame(类StartUpWindow扩展JFrame)和一些选项,然后用户单击一个按钮,JFrame应该关闭,一个新的(MainWindow类)应该打开。

I have a netbeans Java application that should display a JFrame (class StartUpWindow extends JFrame) with some options when the application is launched, then the user clicks a button and that JFrame should be closed and a new one (class MainWindow) should be opened.

那我该如何正确地做到这一点。我显然在StartupWindow的按钮上设置了一个单击处理程序但是我在这个处理程序中放了什么以便我可以关闭StartUpWindow并打开MainWindow?似乎线程也会出现这种情况,因为每个窗口似乎都有自己的线程......或者是JFrames自己处理的线程问题...

So how do I do this correctly. I obviously set a click handler on the button in StartupWindow but what do I put in this handler so that I can close the StartUpWindow and open the MainWindow? It seems that threading comes into this too as every window seems to have their own thread...or are threading issues automatically handled by JFrames themselves...

推荐答案

以下是一个例子:

StartupWindow.java

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;


public class StartupWindow extends JFrame implements ActionListener
{
    private JButton btn;

    public StartupWindow()
    {
        super("Simple GUI");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        btn = new JButton("Open the other JFrame!");
        btn.addActionListener(this);
        btn.setActionCommand("Open");
        add(btn);
        pack();

    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
        String cmd = e.getActionCommand();

        if(cmd.equals("Open"))
        {
            dispose();
            new AnotherJFrame();
        }
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable(){

            @Override
            public void run()
            {
                new StartupWindow().setVisible(true);
            }

        });
    }
}

AnotherJFrame.java

import javax.swing.JFrame;
import javax.swing.JLabel;

public class AnotherJFrame extends JFrame
{
    public AnotherJFrame()
    {
        super("Another GUI");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        add(new JLabel("Empty JFrame"));
        pack();
        setVisible(true);
    }
}

这篇关于Java swing应用程序,关闭一个窗口,单击按钮时打开另一个窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆