1

This is my first swing application. I'm trying to create an window and add a button. On clicking the button, it should display some value on the console. Everythign works fine, but the window is very small. I've specified 800*600, but then also the window size is small, that is its wrapping the button size only.

Here is my code snippet:

JFrame frame = new JFrame("My Application");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container contentPane = frame.getContentPane();
contentPane.setLayout(new BorderLayout());
contentPane.add(new MyClass(), BorderLayout.CENTER);
frame.setSize(800, 600);
frame.pack();
frame.setVisible(true);

Snippet from MyClass.java:

setLayout(new GridBagLayout());
JButton button = new JButton("Button");
button.addActionListener(this);
add(button);

How to make the window size as 800*600?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • this is what you need http://stackoverflow.com/questions/8193801/how-to-set-specific-window-frame-size-in-java-swing – vikeng21 May 30 '14 at 09:43
  • 1) For better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete and Verifiable Example). 2) Provide ASCII art (or an image with a simple drawing) of the GUI as it should appear in smallest size and (if resizable) with extra width/height. – Andrew Thompson May 30 '14 at 09:53

3 Answers3

3

The pack() method should always be called on a GUI based on a JFrame, so leave that in. It reduces the GUI to the smallest size needed to display the components in it. But don't go calling setSize(Dimension) after that, before checking it is larger than the minimum size.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
0

Remove frame.pack(); from your code.

More information:

http://docs.oracle.com/javase/tutorial/uiswing/components/frame.html

http://docs.oracle.com/javase/6/docs/api/java/awt/Window.html#pack%28%29

Gokul Nath KP
  • 15,485
  • 24
  • 88
  • 126
0

You are calling pack method. The api said: "It causes this Window to be sized to fit the preferred size and layouts of its subcomponents"

You haven't specified the preferred size. Try it doing this:

frame.setPreferredSize(new Dimension(800,600));

The_Reaper
  • 157
  • 10
  • 1
    See [Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?](http://stackoverflow.com/q/7229226/418556) (Yes.) – Andrew Thompson May 30 '14 at 09:51