Jump to content

Check out our Community Blogs

Register and join over 40,000 other developers!

Recent Status Updates

View All Updates

- - - - -

Why does this JButton take up the entire screen?

jbutton setpreferredsize

  • Please log in to reply
1 reply to this topic

#1 Nickburris


    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 03 February 2011 - 06:03 PM

When I run this code, the JButton b1 appears on the screen but the button is taking up the entire screen, instead of the set size 50x50..

Icon sb = new ImageIcon(getClass().getResource("Start.png"));
	b1 = new JButton("", sb);
	b1.setPreferredSize(new Dimension(50, 50));
("private JButton b1;" is written at the top of my code)
  • 0

#2 ZekeDragon


    CC Leader

  • Retired Mod
  • PipPipPipPipPipPipPip
  • 1263 posts

Posted 04 February 2011 - 01:30 AM

Did you set a layout in the parent container? There isn't much code, this is what I wrote as a test and the JButton goes down to it's preferred size as expected:

import javax.swing.*;
import java.awt.*;

public class JButtonTest
    public JButtonTest()
        JFrame frame = new JFrame();
        frame.setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.LINE_AXIS));
        Icon sb = new ImageIcon(getClass().getResource("Start.png"));
        JButton b1 = new JButton("", sb);
        b1.setPreferredSize(new Dimension(50, 50));

    public static void main(String[] args)
        new JButtonTest();

  • 0
If you enjoy reading this discussion and are thinking about commenting, why not click here to register and start participating in under a minute?

Also tagged with one or more of these keywords: jbutton, setpreferredsize

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download