Question

I have a JPanel and a Jlist, when the user selects a different item in the list, the corresponding component will be added to the panel, while the previous component will be removed. Here is the portion of the code:

depictorPanel.removeAll();
depictorPanel.invalidate();
depictorPanel.repaint();
GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.BOTH;
depictorPanel.add(viewer, constraints);
viewer.setSize(depictorPanel.getSize());
depictorPanel.invalidate();
depictorPanel.repaint();

where the depictorPanel is the JPanel, and the viewer is the component (btw. the viewer is of type VisualizationView coming from the JUNG library, which inherits also JPanel).

When I resize the JPanel (done by resizing the whole window, such that all the components in the window are resized), or minimize the window and restore it, the viewer component is gone, I can tell since I set different background colors of the depictorPanel and the viewer.

I have also handled the componentResized listener of the depictorPanel to invalidate and repaint the viewer, but no luck.

Was it helpful?

Solution

I finally found a working method that uses a layout manager (GridBagLayout):

GridBagConstraints constraints = new GridBagConstraints();
constraints.fill = GridBagConstraints.BOTH;
constraints.gridx = 0;
constraints.gridy = 0;
constraints.weightx = 1;
constraints.weighty = 1;
depictorPanel.add(currentViewer, constraints);
depictorPanel.revalidate();

This code makes the effect that I was expecting. I think my problem was not understanding each individual layout manager that well (since I am relatively new to Java).

Thank you all guys! I do learn something about Java through this question (and SSCCE) :-)

OTHER TIPS

I found a workaround to my problem, that is, manage the layout manually without using any layout manager (set the location and size manually and resize when the depictorPanel is resized).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top