JPanel不使用setSize和setPrefferedSize

8 java swing jpanel

请解释为什么它不起作用,也可以发布解决方案来解决这个问题.非常感谢你提前.

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Mad*_*mer 8

问题是,JFrame使用a BorderLayout,它将尝试调整内容的大小以适应父容器.虽然BorderLayout将尝试使用首选大小作为提示,但如果可用空间大于或小于,则它将自动调整以允许中心内容(默认位置)填充父容器的整个可用空间.

您可以尝试使用a FlowLayoutGridBagLayout更有可能在更多情况下遵循首选大小

请查看如何在容器上布置组件以获取更多详细信息

  • 这完全取决于您要做什么。一个不错的起点是[Java Tutorials](http://docs.oracle.com/javase/tutorial/),尝试一些东西并提出问题;)-我还要说,这是最大的优点之一开发人员具有研究问题,寻找已经提出的问题的答案的能力。准备抛弃思路或发展以寻求更好解决方案的能力也很重要,而且要知道何时才能这样做。对[Design Patterns](http://www.oodesign.com/)的理解将使您处于稳定状态,而不必考虑劳资;) (2认同)

Chr*_*ian 5

你可以使用pack()方法.来自Java Docs:

public void pack(): 使此窗口的大小适合其子组件的首选大小和布局....


您应该在构造函数的末尾使用此方法:

...
setLocationRelativeTo(null);
setVisible(true);
pack();
Run Code Online (Sandbox Code Playgroud)

编辑:

如果您希望JFrame保持大小,JPanel也要保持大小.您可以尝试以下方法:

  • 创建一个JPanel并将其添加到JFrame.请注意,此面板将调整大小
  • 创建第二个JPanel并将其添加到以前的JPanel,因此它将保持其大小.

像这样的东西:

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

    /** JPanel Properties **/
    jpanel2.setBackground(Color.red);
    jpanel2.setPreferredSize(new Dimension(50, 50));
    jpanel.add(jpanel2);        

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

    /** JFrame Properties **/
    ...
}
Run Code Online (Sandbox Code Playgroud)

Edit2:你也可以尝试绝对定位:

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

    jpanel.setLayout(null);

    Insets insets = jpanel2.getInsets();
    Dimension size = jpanel2.getPreferredSize();
    jpanel2.setBounds(125 + insets.left, 100 + insets.top, size.width, size.height);

    /** JPanel Properties **/
    jpanel2.setBackground(Color.red);
    jpanel.add(jpanel2);

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

    /** JFrame Properties **/
    ...
}
Run Code Online (Sandbox Code Playgroud)