Java Swing question

I’m creating a prototype user interface for a program, which currently contains a menubar, a JPanel, and a JTextArea.

When I run it, all that gets displayed is the Text Area but not the JPanel with all the labels.

Originally I was using ImageIcons for the labels, but for debugging purposes I changed to using text only labels, and commented out the image icons being created.

I am using pack, and set visible and I’ve tried validate. This isn’t an applet just an application. Anyone got any idea why my JPanel isn’t showing up?


paintPanel = new JPanel(new GridLayout(20, 20));

// populate the grid with dummy icons until full implementation is underway
   // then the JPanel will be filled from Simulation

/* ImageIcon icon1 = new ImageIcon("~/documents/source/politician.jpg");
ImageIcon icon2 = new ImageIcon("~/documents/source/lobbyist.jpg");
ImageIcon icon3 = new ImageIcon("~/documents/source/dollar.jpg");*/

for(int i = 0; i < 20; i++)
{
	for(int j = 0; j < 20; j++)
	{
		if((20 * i + j) % 6 == 0)
			paintPanel.add(new JLabel("A"));
		else if((20 * i + j) % 6 == 1)
			paintPanel.add(new JLabel("B"));
		else if((20 * i + j) % 6 == 2)
			paintPanel.add(new JLabel("C"));
		else
			paintPanel.add(new JLabel(" "));
	}
}
	
paintPanel.validate();
paintScroll = new JScrollPane(paintPanel);
frame.getContentPane().add(paintScroll);
	
log = new JTextArea("Political Predator Prey System

A group two production.");
textScroll = new JScrollPane(log);
frame.getContentPane().add(textScroll);

I figured it out. The default layout for a content pane of a JFrame must be bad or something. Finally I figured out that I needed to set that layout as well as the JPanel layout and everything finally showed up on the screen.

Like all bugs there is a :smack: :smack: :smack: moment at how simple it is in the end.

You got it. Just so you don’t wonder what the “must be bad or something” part of the problem is, here goes:

First your code:



paintPanel.validate();
paintScroll = new JScrollPane(paintPanel);
frame.getContentPane().add(paintScroll);

log = new JTextArea("Political Predator Prey System
A group two production.");
textScroll = new JScrollPane(log);
frame.getContentPane().add(textScroll);


You have called “add” on the JFrame’s content pane twice with no constraints.

The default layout manager of a JFrame is BorderLayout.

From the JDK docs on BorderLayout:

Hence, you have added one component to CENTER, followed by adding another component to CENTER. In essence, you have overwritten paintScroll with textScroll.