问题
I am making a JFrame with the size of 500x500 pixels. I make a blue background and add a red square in the right-bottom corner from (490,490) to (500,500).
Image:
I don't see the red square on the screen. I switched the frame from not resizable to resizable and if I make the window larger the red dot is there. Is the frame size the same as application's window size? How can I make the application's window to be the exactly 500x500?
回答1:
The frame is the size of the entire window, including the title bar required by the OS. When drawing things in the JPanel in the JFrame, the (0, 0) coordinate is in the top left corner if the JPanel, which begins just below the title bar. It sounds like your title bar is taller than 10 pixels, so 490 as a y component is actually off the window, since the visible height of the JPanel is windowHeight - titleBarHeight.
回答2:
Your content pane should override the getPreferredSize() method, returning a Dimension object with width and height of 500 pixels:
public class MyContentPane extends JPanel {
private Dimension dimension;
public MyContentPane() {
this.dimension = new Dimension(500, 500);
}
@Override
public Dimension getPreferredSize() {
return this.dimension;
}
}
// How to use your new class
SwingUtils.invokeLater(() -> {
JFrame frame = new JFrame("Title");
frame.setContentPane(new MyContentPane());
frame.pack();
frame.setVisible(true);
});
The size of your JFrame will be calculated by Swing by taking in consideration the preferred size of the components inside it.
回答3:
Should user the following
@Override
PreferedSize()
Remember preferedSize method is method of the super class JFrame.
回答4:
this may be useful for you?
JPanel aa = new JPanel(new GridBagLayout());
aa.setMaximumSize(new Dimension(500,500));
aa.setMinimumSize(new Dimension(490,490));
aa.setBorder(BorderFactory.createLineBorder(Color.black));
来源:https://stackoverflow.com/questions/31013830/java-jframe-setsize-doesnt-work-properly