我试图在java中创建一个GUI,其中包含一个JComboBox和JList,其内容根据JComboBox中选择的项目而变化。
我想添加一个scroolPane到JList。我将向您展示代码和图像来澄清这个问题:
JPanel listPanel = new JPanel();
Hashtable<String, String[]> subItems = new Hashtable<String, String[]>();
JComboBox<String> tendina;
JList<String> subList;
GridBagConstraints c;
String ricevuti[] = {"Alex", "Ben", "Claire", "Dana", "Ellen", "Felicia", "Gary", "Hailey", "Imogen", "Jay", "Kate", "Alex", "Ben", "Claire", "Dana", "Ellen", "Felicia", "Gary", "Hailey", "Imogen", "Jay", "Kate"};
JList ricList = new JList(ricevuti);
String inviati[] = {"Lara", "Megan", "Nikole", "Oscar", "Paige", "Quentin", "Ralph", "Sara", "Thelma", "Victoria", "William"};
JList invList = new JList(inviati);
String ricInv[] = {"Seleziona un item..", "Ricevuti", "Inviati"};
Inbox() {
//...
listPanel.setLayout(new GridBagLayout());
listPanel.setBackground(Color.BLUE);
/*** ComboBox ***/
tendina = new JComboBox<String>(ricInv);
tendina.addActionListener(this);
tendina.setEditable(false);
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = 1;
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(-295, 10, 0, 0); //top, left, bottom, right
c.weightx = 1;
listPanel.add(tendina, c);
/*** Lista ***/
subList = new JList<String>();
subList.setPreferredSize(new Dimension(80, 280));
subList.setVisibleRowCount(10);
subList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
JScrollPane scrollList = new JScrollPane(subList);
subItems.put(ricInv[1], ricevuti);
subItems.put(ricInv[2], inviati);
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridwidth = 1;
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(30, 10, 0, 0); //top, left, bottom, right
c.weightx = 1;
**[1]**listPanel.add(subList, c);
**[2]**listPanel.add(scrollList, c);
//...
}
问题是,当我添加scrollList[2]到listPanel,布局是混乱的。如果我将子列表[1]添加到listPanel,那么布局是正确的,但显然我没有滚动列表。
如何添加scrollList而不改变布局?
如果我将subList添加到listPanel[1]会发生什么:http://www.mediafire.com/view/daye4rkx1tyhwbq/sublist.png
如果我将scrollList添加到listPanel[2],会发生这样的情况:http://www.mediafire.com/view/jfiky6j686e2h58/scroll.png
感谢关于高度,我意识到问题取决于subList.setVisibleRowCount(16);
。
但是我怎么调整宽度呢?
这不是我在上一篇文章中给你的建议:http://docs.oracle.com/javase/tutorial/uiswing/events/documentlistener.html
包含JList的JScrollPane应该从一开始就使用您想要的布局添加到您的GUI中。
然后使用setModel(...)
方法更改JList中的数据。