I have a swing application in which I display images in a JPanel. If the app is unable to produce the image I want to remove the previous one from the JPanel and replace it with a JTextField and message. I can add the text field , but it's drawn on top of the previous contents, which is itself a subclass of JPanel. Here's what I have:
private void displayMessage(String message) {
JTextField tf = new JTextField(message);
cdPanel.removeAll();
cdPanel.add(tf, BorderLayout.NORTH);//tried lots of variations, inc. no layout
cdPanel.validate();
}
How can I get cdPanel to completely redraw itself?
The answer is pretty simple. Use getComponents() to iterate through an array of components added to the JPanel. Find the kind of component you want to remove, using instanceof for example. In my example, I remove any JCheckBoxes added to my JPanel.
Then the answer to your question is no, there is no other way to do this, the API was designed from the start to make use of the layout managers.
It allows you to group components together, it allows you to devise complex interfaces, as each panel can have a different layout, allowing you to leverage the power of different layout managers.
Layout Managers in Swing The "layout" of a content pane (JPanel), is the arrangement of its components (text, images, buttons, checkboxes, radio buttons, etc.). Luckily, Java provides some pre-designed patterns for arranging the display (order) of components, referred to as Layout Managers.
You can simply try calling :
cdPanel.revalidate();
cdPanel.repaint(); // This is required in some cases
instead of
cdPanel.validate();
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