Java swing 应用程序,单击按钮时关闭一个窗口并打开另一个窗口

标签 java swing

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

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

最佳答案

这是一个例子:

enter image description here

enter image description here

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);
            }

        });
    }
}

另一个JFrame.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 应用程序,单击按钮时关闭一个窗口并打开另一个窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9572931/

相关文章:

java - 填充 JComboBox 时遇到困难

java - 使用 NIO 和 Channel 系统将流写入文件

java - iText7 - Html2Pdf Jar 和源代码

java - 将 MySQL DB 对象与 Java 中的字符串进行比较

java - 无法解析 Criteria API 中的嵌入实体

Java 小程序 Jbutton 错误

Java:如何从内部类中的方法返回外部方法

Java:如何在打开另一个 JFrame 时关闭它?

Java Graphics,使用点击事件改变绘图的颜色

Java 1.5 gc 调整