0

我有这个Actionlistener将我以前的面板更改为第二个面板,现在我想在其中放置一个“返回”按钮panel2,让我回到panel1维护其图形设置。

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JFrame {

private static final long serialVersionUID = 1L;
    public static void main(String[] args){
        final JFrame Main = new JFrame("TEST");
        Main.setVisible(true);
        Main.setSize(600, 600);
        Main.setLocationRelativeTo(null);
        Main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);    

//Adding JPanel     
        JPanel panel = new JPanel();
        Main.add(panel);

//JPanel settings
        panel.setLayout(null);
        panel.setBackground(Color.GREEN);

//Adding JButton
        JButton button = new JButton("Button 1");
        JButton button2 = new JButton("Button2");
        panel.add(button);
        panel.add(button2);

//JButton settings
        button.setBounds(70, 160, 200, 200);
        button2.setBounds(320, 160, 200, 200);

//Button action
button.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e) {

        JPanel panel2 = new JPanel();

        //Panel2 settings
        JButton button3 = new JButton("Back");
        panel2.add(button3);
        panel2.setBackground(Color.RED);

        Main.getContentPane().removeAll();
        Main.getContentPane().add(panel2);
        Main.getContentPane().validate();

    }
});

//Button action
button2.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e) {

        JPanel panel3 = new JPanel();

        //Panel2 settings
        JButton button3 = new JButton("Back");
        panel3.add(button3);
        panel3.setBackground(Color.YELLOW);

        //Button action
        button3.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {

                JPanel panel = new JPanel();

                Main.getContentPane().removeAll();
                Main.getContentPane().add(panel);
                Main.getContentPane().validate();

                    }

                });

        Main.getContentPane().removeAll();
        Main.getContentPane().add(panel3);
        Main.getContentPane().validate();

            }

        });

    }
}
4

0 回答 0