I get a JFrame and i want to display a JLabel with a border in it with a padding of maybe 50px. When i set the size of the JFrame to 750, 750, and the size of the JLabel to
First get the pixels trimmed out by the frame.
int reqWidth = reqHeight = 750;
// first set the size
frame.setSize(reqWidth, reqHeight);
// This is not the actual-sized frame. get the actual size
Dimension actualSize = frame.getContentPane().getSize();
int extraW = reqWidth - actualSize.width;
int extraH = reqHeight - actualSize.height;
// Now set the size.
frame.setSize(reqWidth + extraW, reqHeight + extraH);
An alternate simpler way. The previous works but this is recommended.
frame.getContentPane().setPreferredSize(750, 750);
frame.pack();
Hope this helps.
EDIT:
Add this in your constructor before adding components to the frame. and to set it in the middle, use
frame.setLocationRelativeTo(null);
This will center the window on the screen.
Using setPreferredSize()
is problematic, as it always overrules the component's calculation with an arbitrary choice. Instead, pack()
the enclosing Window
to accommodate the preferred sized of the components, as shown below.
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.border.CompoundBorder;
/**
* @see https://stackoverflow.com/a/13481075/230513
*/
public class NewGUI extends JPanel {
private static final int S1 = 10;
private static final int S2 = 50;
private JLabel label = new JLabel("Hello, world!");
public NewGUI() {
label.setHorizontalAlignment(JLabel.CENTER);
Border inner = BorderFactory.createEmptyBorder(S1, S1, S1, S1);
Border outer = BorderFactory.createLineBorder(Color.black);
label.setBorder(new CompoundBorder(outer, inner));
this.setBorder(BorderFactory.createEmptyBorder(S2, S2, S2, S2));
this.add(label);
}
private void display() {
JFrame f = new JFrame("NewGUI");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(this);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
new NewGUI().display();
}
});
}
}