I have made an array of JButtons arranged in a 2x3 box encased in a JPanel with GridLayout. This works fine. But i want to add a JLabel with text under this panel. Problem is that the JLabel, represented here by itemsInfo will not show, and I can't figgure it out why. Also I want to include the first panel and this JLabel in a second Panel, called wholeItems. Please help. And yes I know that GridLayout on the second Panel is not desirable. But it still doesn't show the JLabel.

Code below:

for(int i=0; i<items.length; i++) {
			items[i] = new JButton();
			items[i].setPreferredSize(new Dimension(50, 50));
			items[i].setBackground(new Color(220, 140, 10));
			itemsPanel.add(items[i]);
		}
		
		itemsInfo = new JLabel("abc");
		itemsInfo.setBackground(new Color(230, 50, 60));
		
		wholeItems = new JPanel();
		wholeItems.setLayout(new GridLayout(2,1));
		wholeItems.add(itemsPanel);
		wholeItems.add(itemsInfo);

Recommended Answers

All 5 Replies

Maybe the problem is at a higher level - the top-level container. Do you add wholeItems to that (not itemsPanel!), do you pack() it afterwards?

Maybe the problem is at a higher level - the top-level container. Do you add wholeItems to that (not itemsPanel!), do you pack() it afterwards?

Well this is ebarassing... I could swear I added wholeItems to the main panel. Turns out I didn't added it. Thanks

Also, how can I make the two stack up nicely one on top of the other using BoxLayout or some other layout?

Try using a BoxLayout instead of GridLayout:

//wholeItems.setLayout(new GridLayout(2,1)); --> replace this line with:
wholeItems.setLayout(new BoxLayout(wholeItems, BoxLayout.Y_AXIS));

This assumes that the buttons are packed into a grouped some how, I would use a Box - javax.swing.Box; - with a GridLayout. Once you have that than you can safely add the Box and the JLabel to the panel with BoxLayout in the Y_AXIS(wholeItems). Than add that panel to a top container and you should be good to go. :)

Thank you for the help. Yes, the 6 buttons were already inside a JPanel, with a GridLayout(2,3)

Member Avatar for hfx642

Instead of wholeItems having a GridLayout, try using a BorderLayout.
Put your buttons in the CENTER and your itemsInfo label SOUTH.
(Then, I usually wrap the whole thing in a FlowLayout panel.)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.