可能重复:
Swing: How do I set a component height to the container's height?
如何划分JPanel,如下图所示,有2个面板panel1和panel2 panel1应占70%,panel2占30%或panel1应大于panel2 ... 我已经尝试了Gridlayout,边框布局,但它不工作。任何帮助将不胜感激。
public class TestApplication extends JApplet {
private static final long serialVersionUID = 1L;
JPanel p1,p2;
public void init(){
setLayout(new GridLayout(3,1));
p1=new JPanel();
p2=new JPanel();
p1.setBackground(Color.RED);
p2.setBackground(Color.GREEN);
add(p1);
add(p2);
}
}
答案 0 :(得分:14)
您是否考虑过使用JSplitPane
(How to Use Split Panes)?
import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.JApplet;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
public class TestApplication extends JApplet {
private static final long serialVersionUID = 1L;
JPanel p1,p2;
@Override
public void init(){
setLayout(new BorderLayout());
p1=new JPanel();
p2=new JPanel();
p1.setBackground(Color.RED);
p2.setBackground(Color.GREEN);
JSplitPane sp = new JSplitPane(JSplitPane.VERTICAL_SPLIT);
sp.setResizeWeight(0.7);
sp.setEnabled(false);
sp.setDividerSize(0);
sp.add(p1);
sp.add(p2);
add(sp, BorderLayout.CENTER);
}
}
答案 1 :(得分:1)
如果你有一个外部JFrame(或另一个JPanel)f,你可以应用BorderLayout并将p1放在NORTH中,将p2放在SOUTH中。然后,使用
Dimension df = f.getSize();
您将获得外部容器的尺寸(f)。 接下来,请致电:
void setSize(Dimension d)
这样:
p1.setSize(new Dimension(df.getWidth(), df.getHeight()*0.7));
p2.setSize(new Dimension(df.getWidth(), df.getHeight()*0.3));
最后,将这些JPanel添加到其容器中。