Reputation: 175
I wrote the following code which is a simple window with a JLabel header at the top. The code is as follows:
import java.awt.Color;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class Main extends JFrame {
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
init();
}
public Main() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
int WIDTH = 500;
int HEIGHT = 500;
setBackground(Color.LIGHT_GRAY);
setSize(WIDTH, HEIGHT);
setTitle("New Window");
setLocationRelativeTo(null);
JPanel pane = new JPanel();
pane.setOpaque(false);
setContentPane(pane);
pane.setLayout(null);
JLabel title = new JLabel("New Window", SwingConstants.CENTER);
title.setFont(new Font("Neuropol", Font.PLAIN, 22));
title.setSize(WIDTH, 20);
title.setBorder(BorderFactory.createLineBorder(Color.black));
pane.add(title);
}
static void init() {
Main frame = new Main();
frame.setVisible(true);
}
}
I'm having a weird issue with it though. As you can see I set the width of the JLabel to the same width as the JFrame (and therefore the same width as the JPanel), but for some reason, the label goes past the right edge of the Frame. The width of the frame is 500, but I have to set the JLabel to a width of 483 in order for the border to be within the JFrame. I've been over and over this, but can't see anything wrong. Does anybody see my mistake here?
Upvotes: 0
Views: 1134
Reputation: 324118
I set the width of the JLabel to the same width as the JFrame
But the JFrame width includes the "decorations" of the frame, like the Border.
I have to set the JLabel to a width of 483 in order for the border to be within the JFrame.
No, 483 will make the label too big for the frame. The Borders of the frame are not 17 pixels. I think the Borders are 4 or 5 pixels each depending on the LAF.
So this is another reason why you should NOT be using a null layout as hardcoding a value for one LAF may not work on another LAF.
Also, what happens if the user resizes the frame wider? Now the label will not go to the end. Use a Layout Manager do design dynamic GUI's that adapt to changes as the user resizes the frame.
The easiest solution is to just use the default BorderLayout of content pane of the frame. Then you add your label to the PAGE_START
.
add(title, BorderLayout.PAGE_START);
There is also no reason to create a content pane. The frame already has a JPanel which uses a BorderLayout.
Read the Swing tutorial on Layout Managers for more information and working examples. Download the demos code and use them as a starting point for your code. The demo code will show you how to better structure your code to follow Swing conventions.
Upvotes: 3