简体   繁体   中英

Java JFrame setSize doesn`t work properly

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: http://imageshack.com/a/img913/7936/7ZdxvR.png

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?

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.

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 ay component is actually off the window, since the visible height of the JPanel is windowHeight - titleBarHeight .

Should user the following

@Override
PreferedSize()

Remember preferedSize method is method of the super class JFrame.

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM