在JFrame中放置和调整JPanel的大小

时间:2013-07-07 07:35:17

标签: java swing jpanel layout-manager

我希望JFrame的{​​{1}}看起来像这样。

Sample layout

左侧的2个面板宽度为60%,高度为50%,然后右侧的面板宽度为40%,高度为100% 我怎样才能做到这一点?

JPanel

2 个答案:

答案 0 :(得分:3)

您永远不应手动控制尺寸。如果用户想调整大小怎么办?你必须做无用的计算,而java会很乐意使用布局管理器为你做这件事。

http://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html

答案 1 :(得分:-1)

JFrame frame = new JFrame();
frame.setLayout(null);
frame.setSize(600, 400);

JPanel panel1 = new JPanel();
panel1.setBounds(0, 0, 400, 200);
panel1.setBackground(Color.YELLOW);
panel1.setLayout(null);

JPanel panel2 = new JPanel();
panel2.setBounds(400, 0, 200, 400);
panel2.setBackground(Color.RED);
panel2.setLayout(null);

JPanel panel3 = new JPanel();
panel3.setBounds(0, 0, 600, 400);
panel3.setBackground(Color.BLACK);
panel3.setLayout(null);

panel3.add(panel1);
panel3.add(panel2);
frame.add(panel3);

//YOU CAN USE  LAYOUT = NULL TO MANUALLY POSITION YOUR PANELS
//IT IS BEST TO USE LAYOUT MANAGERS, BUT SETTING THE POSITIONS MANUALLY IS THE EASIEST
//SPECIALLY IF YOU WILL JUST .setResizable(false)