I want to replace a Jpanel with another one in a JFrame I already search and try my code but nothing\'s happen this is my code :
public class Frame extends
Several issues with your code. Here is fixed version:
public class Frame extends JFrame {
private Container contain;
private JPanel reChange,reChange2;
private JButton reChangeButton;
public Frame() {
super("Change a panel");
setSize(350, 350);
getContentPane().setLayout(null); // Changed here
setLocationRelativeTo(null);
setResizable(false);
reChange = new JPanel(null);
reChange.setBackground(Color.red);
reChange.setSize(240, 225);
reChange.setBounds(50, 50, 240, 225);
getContentPane().add(reChange); // Changed here
reChangeButton = new JButton("Change It");
reChangeButton.setBounds(20, 20, 100, 20);
getContentPane().add(reChangeButton); // Changed here
reChangeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
contain = getContentPane();
contain.removeAll();
reChange2 = new JPanel(null);
reChange2.setBackground(Color.white);
reChange2.setSize(240, 225);
reChange2.setBounds(50, 50, 240, 225);
contain.add(reChange2);
invalidate(); // Changed here
repaint(); // Changed here
}
});
}
public static void main(String[] args) {
Frame frame = new Frame();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}