Java – JPanel does not use SetSize and setprefferedsize

Please explain why it doesn't work. You can also publish a solution to solve this problem Thank you very much for your advance

public class Run extends JFrame{

    /** Fields **/
    static JPanel jpanel;
    private int x,y;

    /** Constructor **/
    public Run() {
        /** Create & Initialise Things **/
        jpanel = new JPanel();
        x = 400; y = 400;

        /** JPanel Properties **/
        jpanel.setBackground(Color.red);
        jpanel.setPreferredSize(new Dimension(20,30));


        /** Add things to JFrame and JPanel **/
        add(jpanel);

        /** JFrame Properties **/
        setTitle("Snake Game");
        setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
        setCursor(null);
        setResizable(false);
        setSize(new Dimension(x,y));
        setLocationRelativeTo(null);
        setVisible(true);
    }

    /** Set the Cursor **/
    public void setCursor() {
        setCursor (Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
    }

    /** Main Method **/
    public static void main(String [ ] args) {
        Run run = new Run();
        run.setCursor();
    }
}

Solution

The problem is that JFrame uses borderlayout, which will try to resize the content to fit the parent container Although borderlayout will try to use the preferred size as a hint, if the available space is greater or less, it will automatically adjust to allow the central content (the default location) to fill the entire available space of the parent container

You can try flowlayout or gridbaglayout, which is more likely to follow the preferred size in more cases

For details, see how to layout components on containers

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>