我已经将此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();
}
});
}
}