I got some problems showing the items of a JList.
DefaultListModel<String> model = new DefaultListModel<String>();
model.addElement("one");
model.addElement("two");
model.addElement("three");
list = new JList<String>(model);
list.setCellRenderer(new DefaultListCellRenderer());
list.setVisible(true);
I also tried it without setting a ListCellRenderer
, still no luck.
Can you suggest me what I am doing wrong?
Thanks for your anwsers and comments. The problem was that no list item where shown.
In future I will add a minimal compilable program.
My problem was caused by trying to add a JPanel
to a JDialog
in the constructor, but the JPanel
was null
at this moment because it got initialized in the createUIComponents
method.
A beginner begs your pardon.
This works for me:
public class JListTest implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new JListTest());
}
@Override
public void run() {
JFrame frame = new JFrame(getClass().getSimpleName());
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(640, 480);
frame.setLayout(new BorderLayout(4, 4));
frame.add(getComponent(), BorderLayout.CENTER);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
Component getComponent() {
DefaultListModel<String> model = new DefaultListModel<>();
model.addElement("one");
model.addElement("two");
model.addElement("three");
JList<String> list = new JList<>(model);
list.setCellRenderer(new DefaultListCellRenderer());
list.setVisible(true);
return list;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.