好的,我有一个面板
,我想在上面放置两个面板
,左和右
,这样>右侧面板的宽度应是左侧面板宽度的两倍。
我想在左侧面板中添加一个菜单,所选项目的详细信息将显示在右侧面板中。
其次,当窗口展开时,面板及其组件的大小应按比例增加(如果有任何方法可以达到此目的,请提出!)
我确实尝试过使用 GridBagLayout 但我认为我还不能很好地掌握它。因此,请建议最简单的布局管理器,它可以满足我的目的。
<小时/>编辑:-我在 GRIDBAG 上尝试过的问题
//Set Layout
setLayout(new GridBagLayout());
GridBagConstraints c= new GridBagConstraints();
//Set Layout constraints of components and add them to the MainPanel
c.gridx=0;
c.gridy=0;
c.weightx=0.5;
c.insets= new Insets(5,5,5,5);
c.fill=GridBagConstraints.BOTH;
add(iListPanel);
iListPanel.setBorder(BorderFactory.createTitledBorder("Check") );
GridBagConstraints c1= new GridBagConstraints();
c.gridx=1;
c.gridy=0;
c.weightx=1;
c.insets= new Insets(5,5,5,5);
c.fill=GridBagConstraints.BOTH;
add(iDetailsPanel);
iDetailsPanel.setBorder(BorderFactory.createTitledBorder("Check"));
最佳答案
在 Java 附带的布局管理器中,我认为 GridBagLayout 是最简单的一个。值得花时间学习它,因为它是唯一一个半能胜任的布局管理器。这应该可以做到:
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());
GridBagConstraints c;
JPanel left = new JPanel();
left.setBorder(BorderFactory.createTitledBorder("Left"));
c = new GridBagConstraints();
c.weightx = 1;
c.weighty = 1;
c.fill = c.BOTH;
panel.add(left, c);
JPanel right = new JPanel();
right.setBorder(BorderFactory.createTitledBorder("Right"));
c = new GridBagConstraints();
c.weightx = 2;
c.weighty = 1;
c.fill = c.BOTH;
panel.add(right, c);
但是,从你的问题描述来看,听起来像 JSplitPane
会为此更好地为您服务。它是一个现成的组件,可以或多或少地完成您所要求的操作,并且还具有用户可调整大小的分隔符。一个例子:
JSplitPane pane = new JSplitPane();
pane.setResizeWeight(1/3f); // right will be twice size of left
JPanel left = new JPanel();
left.setBorder(BorderFactory.createTitledBorder("Left"));
pane.setLeftComponent(left);
JPanel right = new JPanel();
right.setBorder(BorderFactory.createTitledBorder("Right"));
pane.setRightComponent(right);
<小时/>
编辑:原始代码的问题是它没有使用约束。
add(iListPanel);
应该是:
add(iListPanel, c);
对于iDetailsPanel
也是如此。
关于java - 请建议我使用 GridBag 布局之外的基本布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23448278/