Reputation: 197
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();
}
}
Upvotes: 0
Views: 4502
Reputation: 208944
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.
See Laying out Components within a Container for more details.
Also see Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?
Also have a look at this answer for a quick overview of which layouts will respect the preferred sizes of components and which ones wont.
Also, generally, you should always set your frame visible after adding all your components.
Also, swing apps should be run on the Event Dispatch Thread(EDT). See more at Initial Threads
Upvotes: 1
Reputation: 12363
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
Upvotes: 0
Reputation: 11577
Never use panel.setSize(100,100);
instead use panel.setPreferredSize(100,100);
Also setSize should come after setVisible method.
Upvotes: 2