0

I'm totally new at Java, and I'm trying to write my first program..

But I've already run into the first problem that I can't seem to find the answar to at google.

I have made a JFrame and a JPanel inside of it.

I want the panel to be a specific size, but when I try to set the size of the panel, it doesn't work, and the panel just fits the size of the frame.

package proj;

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

class Program {
    Program() {
        JFrame frame = new JFrame("Mit program");
        frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        frame.setSize(600, 400);
        frame.setResizable(false);

        JPanel panel = new JPanel();
        panel.setVisible(true);
        panel.setSize(100,100); // <- Why doesn't this work?
        panel.setBorder(BorderFactory.createLineBorder(Color.black));
        frame.add(panel);
    }
}

public class Proj {
    public static void main(String[] args) {
        new Program();
    }
}
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Zjitzu
  • 187
  • 1
  • 3
  • 11
  • most of the time the frame is the one that is doing the resizing, not the panel. – user2277872 Apr 25 '14 at 12:16
  • Try not setting the size of the JFrame and look at using setMinimumSize() setMaximumSize() and setPrteferredSize() http://docs.oracle.com/javase/7/docs/api/javax/swing/JPanel.html – onesixtyfourth Apr 25 '14 at 12:17

3 Answers3

2

Never use panel.setSize(100,100); instead use panel.setPreferredSize(100,100); Also setSize should come after setVisible method.

rogue-one
  • 11,259
  • 7
  • 53
  • 75
  • [Don't use `setPreferredSize()` when you really mean to override `getPreferredSize()`](http://stackoverflow.com/q/7229226/230513). – trashgod Apr 25 '14 at 12:25
1

Don't worry about setting the size or even setting the preferred size, as other answers have suggested (unless you're doing custom painting, in which case you'll want to override getPreferredSize() instead of setPreferredSize()).

You should instead use Layout Managers to take care of the sizing and laying out of components for you. When you add compoenents to your panel, the preferred size of the panel will be taken care of for you.

Also in your current case, the frame has a default BorderLayout, which doesn't respect preferred sizes, so even setPreferredSize won't work, since you set the size of your frame.

Community
  • 1
  • 1
Paul Samsotha
  • 205,037
  • 37
  • 486
  • 720
0

You can set a preferred size like this

panel.setPreferredSize(new Dimension(100, 100));
frame.add(panel);
frame.pack();

This is because most of the time the size is dictated by the layout manager. Also add the pack function.

Ideally you should use layout manager for this purpose. http://docs.oracle.com/javase/tutorial/uiswing/layout/using.html#sizealignment

AurA
  • 12,135
  • 7
  • 46
  • 63