I am trying to add information from a textbox into jlist though i doesnt seem to work.
I initialize the JList here:
textField = new JTextField();
textField.setColumns(10);
btnAdd = new JButton("Add");
JButton btnRun = new JButton("Run");
listIn = new JList();
listIn.setBorder(new LineBorder(new Color(0, 0, 0)));
Then add an action to a button to get the text from the textField
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
listIn.addElement(textField.getText()); //This is what i assume it has to be , but it does not recognize the method "addElement"
}
});
Am i initializing the JList wrong ?
Define proper list model to add elements
DefaultListModel<String> model = new DefaultListModel<>();
JList<String> listIn = new JList<>( model );
And then add it in the action
model.addElement(textField.getText());
Read the section from the Swing tutorial on How to Use Lists .
The ListDemo
is a working example that shows you how to both "add" and "remove" items from a JList. It will also show you how to better structure your code so the GUI is created on the Event Dispatch Thread (EDT).
Keep a link to the tutorial handy for all the Swing basics.
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.