Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

swing - How to go back to the previous GUI when a button is clicked in Java

I have a Java application that should display Gui1 then go to Gui 2 which I successful did , Then from Gui2 go back to Gui 1 which I have problems in doing. So how can I go back to Gui 1 when I press a button in Gui2

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 code

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);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Go back previous GUI you can use bellow code:

  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);
    btn1.addActionListener(new Gui2.ButtonListener());
    btn1.setActionCommand("back");
    setVisible(true);
}

private class ButtonListener implements ActionListener {

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

        if (cmd.equals("back")) {
            dispose();

            new Gui1().setVisible(true);
        }
    }
}

}


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...