To add a user-defined array of choices to a JList
in Swing, you can follow these steps:
- Create a
JList
instance and aDefaultListModel
to hold the data:
JList<String> list = new JList<>();
DefaultListModel<String> model = new DefaultListModel<>();
list.setModel(model);
- Create an array of choices and populate the
DefaultListModel
with the array elements:
String[] choices = {"Choice 1", "Choice 2", "Choice 3"};
for (String choice : choices) {
model.addElement(choice);
}
- Add the
JList
to aJScrollPane
to enable scrolling if needed:
JScrollPane scrollPane = new JScrollPane(list);
- Add the
JScrollPane
or theJList
directly to your Swing container:
frame.getContentPane().add(scrollPane); // assuming "frame" is your JFrame instance
By following these steps, you can create a JList
with user-defined choices in Swing.