Java swing应用程序,单击按钮时关闭一个窗口,然后打开另一个窗口
我有一个netbeans Java应用程序,该应用程序在启动时应显示JFrame(StartUpWindow类扩展为JFrame类),并带有一些选项,然后用户单击一个按钮,然后关闭JFrame并打开一个新的(MainWindow类)。
因此,我该如何正确执行此操作。我显然在StartupWindow中的按钮上设置了一个单击处理程序,但是我应该在该处理程序中添加什么以便关闭StartUpWindow并打开MainWindow?似乎每个线程也都有自己的线程…也可能由JFrames自己自动处理线程问题…
回答:
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应用程序,单击按钮时关闭一个窗口,然后打开另一个窗口 的全部内容, 来源链接: utcz.com/qa/432263.html








