I'm trying to add multiple components to a JPanel, but only the most recently added component is displaying.
It seems like the problem is that the layout can only handle 1 component at a time, but I'm at a loss as to how to actually fix it. I've tried adding the components to a separate panel and then adding that to the main panel, and I've tried a few different layouts to no avail.
Here's the relevant code, I'm currently trying just to get two TextRects, which extends JComponent, on the panel:
public class ProjectView extends JFrame implements IProjectView, Observer {
private IProjectModel model;
private ProjectController controller;
private JPanel panel;
public ProjectView(IProjectModel model){
this.model = model;
((Observable) this.model).addObserver(this);
controller = new ProjectController(this.model, this);
addWindowListener(controller);
getContentPane().setLayout(new BorderLayout());
populateMenuBar();
panel = new JPanel(new BorderLayout());
getContentPane().add(panel);
pack();
setMinimumSize(getSize());
setExtendedState(JFrame.MAXIMIZED_BOTH);
}
public void generateUML(ArrayList<ArrayList<String>> content){
panel.add(new TextRect(content.get(0), 10, 10));
panel.add(new TextRect(content.get(0), 100, 100));
panel.revalidate();
}
Any help would be appreciated.
Edit:
generateUML is called from an ActionListener in the controller when the user presses a "Generate UML" button:
private void generateUML(){
ArrayList<IClassModel> classes = new ArrayList<IClassModel>();
classes = model.getClasses();
ArrayList<ArrayList<String>> allClasses = new ArrayList<ArrayList<String>> ();
for(int i = 0 ; i < classes.size() ; i++){
classContent = new ArrayList<String>();
classContent.add(classes.get(i).getClassName());
classContent.addAll(classes.get(i).getMethodNames());
classContent.addAll(classes.get(i).getObjectClasses());
allClasses.add(classContent);
}
System.out.println("1: " + allClasses.get(0));
System.out.println("2: " + allClasses.get(1));
view.generateUML(allClasses);
}
Try this
panel.add(new TextRect(content.get(0), 10, 10), BorderLayout.SOUTH);
panel.add(new TextRect(content.get(0), 100, 100), BorderLayout.CENTER);
panel.revalidate();
panel.repaint()
If you set the BorderLayout, you should use its properties. Also, after calling revalidate(), you should call repaint();
Another option is a GridLayout
panel = new JPanel(new GridLayout(1, 2)); // or 2, 1 depending if you want them
// laid out vertically or horizontally
panel.add(new TextRect(content.get(0), 10, 10));
panel.add(new TextRect(content.get(0), 100, 100));