gpt4 book ai didi

java - 在 GridBagLayout 中填充 JLists

转载 作者:行者123 更新时间:2023-12-04 04:50:50 25 4
gpt4 key购买 nike

我有两个 JLists应该填满 JPanel 中的等量空间与 GridBagLayout .目前它看起来像这样:

enter image description here

如图所示 JList大多数内容都获得了更多空间。试图给他们平等的空间:

bgConstraints.weightx = 0.5;

但剂量似乎并没有像我希望的那样工作。任何想法如何制作这两个 JLists有相同的 width独立于内容和 JFrame 大小(并且不需要更宽)?
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class GridBagTest {

public static void main(String[] arg){
JPanel panel = new JPanel(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.weightx = 0.5;
c.weighty = 1;
panel.add(getList(2),c);
panel.add(getList(10),c);

// Show content
JFrame frame = new JFrame();
frame.add(panel);
frame.pack();
frame.setVisible(true);
}

/**
* Creates a JList
* @param strLength The length of the String in the List
* @return A JList with a String and JScrollPane
*/
private static JScrollPane getList(int strLength){
DefaultListModel<String> listModel = new DefaultListModel<String>();
JList<String> list = new JList<String>(listModel);

String str = "";
for(int i=0; i<strLength; i++)
str += i;

listModel.addElement(str);
JScrollPane pane = new JScrollPane(list);
return pane;
}
}

最佳答案

使用

  • setPrototypeCellValue对于 GridBagLayout 和 JFrame.pack() 接受的初始 PreferredSize;
  • JList进入 JScrollPane ,
  • JTable (with two Column ) instead of two JLists
  • 关于java - 在 GridBagLayout 中填充 JLists,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17464316/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com