Rihards Skrivelis
Rihards Skrivelis

Reputation: 1

Adding Items to JList from textField

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 ?

Upvotes: 0

Views: 8253

Answers (2)

camickr
camickr

Reputation: 324088

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.

Upvotes: 1

StanislavL
StanislavL

Reputation: 57381

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());

Upvotes: 3

Related Questions