I am trying to add a JList to my layout (2 column layout). When added, it makes its entire column take over the entire width of the parent JFrame:
LwjglCanvas c = new LwjglCanvas(blah);
c.getCanvas().setMaximumSize(new Dimension(480, 800)); // explicit width
Box h = Box.createHorizontalBox();
h.add(c.getCanvas());
Box v = Box.createVerticalBox();
h.add(v);
JList list = new JList(mDefaultListModel); // plz use remainder width
v.add(list);
JFrame frame = new JFrame();
frame.setMinimumSize(new Dimension(800, 800));
frame.add(h);
frame.pack();
frame.setVisible(true);
So with the JList added, the right column expands to the full width of the JFrame. I tried wrapping the JList in a JScrollPane, but then my seems to hang upon creation and layout never completes.
What’s the right way to do this?
Thanks
—— Update ————–
I’m giving the JList a bunch of String instances as its data. The strings happen to be pretty long. It looks like what’s happening is that the JList is making itself as wide as the longest string it has to render, ignoring all other layout params. Ideally it would just horizontally scroll instead of growing to the maximum possible width necessary.
—— Update ————–
Finally figured out what was going on. Specifying the size of the JFrame seems to have been causing this behavior. As soon as I removed that line, the JList started rendering as expected. Wrapped it in a JScrollPane, works now too.
Add glue to the layout. Glue will take up the rest of the panel width that’s not being used by your components. So put this line of code in the spot you want taking up the rest of the room in the panel:
Also, as noted in the comments of the question, with the BoxLayout you don’t need any positioning information. So you can simply use this:
h.add(someOtherPanel);instead of this:
h.add(someOtherPanel, BorderLayout.WEST);