如何在JFrame中设置JPanel的大小?

时间:2015-03-12 12:45:25

标签: java swing jframe jpanel

我正在尝试将JPanel放在具有已定义大小的全屏JFrame的中心,但它总是在整个屏幕上拉伸......

我尝试了setBoundssetPreferredSize,但它们无效。

这是代码:

public static void showScene(){
//Create the frame to main application.
    JFrame frame = new JFrame("Application"); // set the title of the frame
    frame.setExtendedState(JFrame.MAXIMIZED_BOTH);  // set the size, maximum size.
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    //Create the panel to store the main menu.
    JPanel panel = new JPanel();

    panel.setPreferredSize(new Dimension(500,200));
    panel.setBackground(new java.awt.Color(0,0,255));

    frame.add(panel,BorderLayout.CENTER);

}

public static void main (String[] args){

    showScene();

}

1 个答案:

答案 0 :(得分:1)

BorderLayout拉伸内容以填充父容器。

如果您希望孩子的尺寸小于父母,请使用其他LayoutManager(尝试FlowLayout)。


您可以使用以下代码更改布局。

Container contentPane = frame.getContentPane();
contentPane.setLayout(new FlowLayout(FlowLayout.CENTER, 0,90)));

frame.add(panel);

frame.pack();

如需进一步参考,请按visual guide to layout managers

祝你好运。