[英]How can I add a scroll on my JList? [JAVA]
Ok, so here's the question. 好的,这就是问题。 I have a JList, where the user is supposed to add some elements, and then the name of the element is displayed on a JList. 我有一个JList,应该向用户添加一些元素,然后在JList上显示元素的名称。 I searched in all the web for adding a scroll on the JList but non of these worked. 我在所有的网络中进行搜索,以在JList上添加滚动条,但是这些滚动条都不起作用。 Can someone help me? 有人能帮我吗? This is the code of the JList, in the method 'initialize()': 这是方法“ initialize()”中JList的代码:
list = new JList();
list.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
if (arg0.getClickCount()==2) {
textFieldRagioneSociale.setText(ragionesociale.get(list.getSelectedIndex()));
textFieldNomeAzienda.setText(nomeazienda.get(list.getSelectedIndex()));
textFieldIndirizzo.setText(indirizzo.get(list.getSelectedIndex()));
textFieldCAP.setText(CAP.get(list.getSelectedIndex()));
textFieldLocalita.setText(localita.get(list.getSelectedIndex()));
textFieldProvincia.setText(provincia.get(list.getSelectedIndex()));
textFieldPartitaIVA.setText(partitaiva.get(list.getSelectedIndex()));
}
}
});
frmCedamClienti.getContentPane().setLayout(null);
list.setBounds(10, 10, 155, 255);
frmCedamClienti.getContentPane().add(list);
You put the JList inside a JScrollPane. 您将JList放在JScrollPane中。
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(list);
...
To make it work, you should add the JList<>()
to your JScrollPane()
. 为了使其工作,您应该将JList<>()
到JScrollPane()
。 Simple way would be as below : 简单的方法如下:
JList list = new JList(new DefaultListModel<>());
Than place your list in JScrollPane()
by : 比通过以下方式将列表放置在JScrollPane()
:
JScrollPane scrollPane = new JScrollPane(list);
Finally, add your JScrollPane()
to contentPane of your JFrame
, simply by : 最后,只需将JScrollPane()
添加到JFrame
contentPane即可:
contentPane.add(scrollPane);
And then, adding items to your JList<>()
would look something like : 然后,将项目添加到您的JList<>()
看起来像:
for (int i = 0; i < 30; i++) {
((DefaultListModel) list.getModel()).addElement(String.valueOf(i));
}
Here you can find full code sample: 在这里您可以找到完整的代码示例:
public TestFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 263, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JList list = new JList(new DefaultListModel<>());
JScrollPane scrollPane = new JScrollPane(list);
scrollPane.setBounds(10, 11, 227, 239);
contentPane.add(scrollPane);
for (int i = 0; i < 30; i++) {
((DefaultListModel) list.getModel()).addElement(String.valueOf(i));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.