Reputation: 11
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. I searched in all the web for adding a scroll on the JList but non of these worked. Can someone help me? This is the code of the JList, in the method 'initialize()':
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);
Upvotes: 1
Views: 1202
Reputation: 317
To make it work, you should add the JList<>()
to your JScrollPane()
.
Simple way would be as below :
JList list = new JList(new DefaultListModel<>());
Than place your list in JScrollPane()
by :
JScrollPane scrollPane = new JScrollPane(list);
Finally, add your JScrollPane()
to contentPane of your JFrame
, simply by :
contentPane.add(scrollPane);
And then, adding items to your JList<>()
would look something like :
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));
}
}
Upvotes: 0
Reputation: 330
You put the JList inside a JScrollPane.
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(list);
...
Upvotes: 2