我正在尝试将JPanel放在具有已定义大小的全屏JFrame的中心,但它总是在整个屏幕上拉伸......
我尝试了setBounds
,setPreferredSize
,但它们无效。
这是代码:
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();
}
答案 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。
祝你好运。