我有一个 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);
}
});
}
}
另一个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/