Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Setting the size of a JButton and JLabel

Status
Not open for further replies.

Stretchwickster

Programmer
Apr 30, 2001
1,746
GB
Hi,

I'm writing an applet and I'm trying to set up a 10x10 grid of JButtons and a 10x10 grid of JLabels, using GridLayout (obviously!). Each JButton and JLabel contains a 10px x 10px ImageIcon, when i run the applet the buttons and labels are not square. I would like them to be 10px x 10px each so that they are the same size as the icon they are displaying. I have tried using the setSize method to no avail! It seems to take no notice of this:

LGrid[j] = new JLabel(icon);
LGrid[j].setSize(new Dimension(10, 10));

BGrid[j] = new JButton(icon);
BGrid[j].setSize(new Dimension(10, 10));

Your assistance would be GREATLY appreciated!! ;-)
 
Hi,

The problem is that GridLayout overrides any Component size methods. If you have set up a 10 * 10 grid, Java will try to resize the Components in the grid to fill the entire size of the Container (Applet).

You could try setting up a Panel with GridLayout, adding your JButtons & JLables to this, setting your Applet to FlowLayout, then adding the Panel to the Applet. The Panel should size to the shape of your JButton/JLabel set, and Flowlayout should not affect the size of the Panel.

Or you can use GridBagLayout which gives fine-grain control over component positioning.

 
Thanx for your reply scrat!

I got it working using a different method - the setPreferredSize method. I basically set the dimensions of the button to the size of the icon (16px x 16px):

BGrid.setPreferredSize(new Dimension(16, 16));
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top