【发布时间】:2015-06-16 07:18:47
【问题描述】:
我有一个 Java 应用程序应该显示 Gui1 然后转到我成功的 Gui 2 ,然后从 Gui2 返回到 Gui 1 我在做时遇到问题。 那么当我在 Gui2 中按下一个按钮时,我怎样才能回到 Gui 1
Gui1 code
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class Gui1 extends JFrame {
private JButton btn=new JButton("Open Gui2");
public Gui1()
{
super(" GUI1");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
btn.addActionListener(new ButtonListener());
btn.setActionCommand("Open");
add(btn);
}
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e)
{
String cmd = e.getActionCommand();
if(cmd.equals("Open"))
{
dispose();
new Gui2();
}
}
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable(){
public void run()
{
new Gui1().setVisible(true);
}
});
}
}
GUI2代码
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Gui2 extends JFrame
{
private JButton btn1= new JButton("Go Back to Gui 1");
public Gui2()
{
super("Another GUI");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
add(btn1);
setVisible(true);
}
}
【问题讨论】:
-
必须保存
Gui1状态? -
顺便说一句:在两个框架中使用
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);会在您设法关闭一个框架时引起不受欢迎的意外。 ;) 另外.. 使用逻辑一致的缩进代码行和块形式。缩进是为了让代码的流程更容易理解!
标签: java swing user-interface