我正在尝试在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。
如何在不更改布局的情况下添加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);
。
但我怎样才能调整宽度?
答案 0 :(得分:0)
这不是我上次发布时给你的建议:http://docs.oracle.com/javase/tutorial/uiswing/events/documentlistener.html
包含JList的JScrollPane应该从一开始就使用您想要的布局添加到GUI中。
然后,您只需使用setModel(...)
方法更改JList中的数据。