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 JFrame {
private Container contain;
private JPanel reChange,reChange2;
private JButton reChangeButton;
public Frame() {
super("Change a panel");
setSize(350, 350);
setLayout(null);
setLocationRelativeTo(null);
setResizable(false);
reChange = new JPanel(null);
reChange.setBackground(Color.red);
reChange.setSize(240, 225);
reChange.setBounds(50, 50, 240, 225);
add(reChange);
reChangeButton = new JButton("Change It");
reChangeButton.setBounds(20, 20, 100, 20);
add(reChangeButton);
reChangeButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//System.out.println("in");
contain = getContentPane();
contain.removeAll();
//System.out.println("in2");
reChange2 = new JPanel(null);
reChange2.setBackground(Color.white);
reChange2.setSize(240, 225);
reChange2.setBounds(50, 50, 240, 225);
//System.out.println("in3");
contain.add(reChange2);
validate();
//System.out.println("in4");
setVisible(true);
//System.out.println("in5");
}
});
}
public static void main(String[] args) {
Frame frame = new Frame();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
can someone help me ? Thanks a lot
Each JPanel object is initialized to use a FlowLayout , unless you specify differently when creating the JPanel . Content panes use BorderLayout by default. If you do not like the default layout manager that a panel or content pane uses, you are free to change it to a different one.
getContentPane(). add(scrollPanel); This code will work in general to add JScrollPane to JPanel. Adjust bounds of frame, panel and scrollpane according to your requirements but ensure that the bounds of JScrollPane are within the bounds of the frame otherwise the scrollpane will not be visible.
JPanel is a subclass of the JComponent, which is a child of the Container; therefore, JPanel is also considered a container. There are many methods used by JPanel, which it inherits from its parent classes.
by giving the JLabel constructor the String argument that is the text to describe what's in there. A JPanel, on the other hand, is a Panel, a designated part of the GUI. Given that it is a distinct part, it is naturally a Container, and should thus be given the stuff.
don't to use AbsoluteLayout
change validate();
in actionPerformed
to contain.validate();
and follows with contain.repaint();
rename class name (reserved Java word, or methods name) Frame
(java.awt.Frame
) to MyFrame
(for example)
use CardLayout
instead of remove and then add a new JPanel
on runtime
You must call validate()
and then repaint()
on the containing panel after you do the remove and add operations.
contain.validate();
contain.repaint();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With