简体   繁体   中英

Adding items to an already existing jlist from another class

I have a jList (named JList1) created using the Desing mode from NetBeans IDE, and I want to add items to that list using a secondary class which parses a big xml list and gets the data from it. My problem is that I dont really understand how to do this, I already tried a lot of different codes, tried with a model too, but cant get it right. I am new to java (and programming too), and I dont understand if I do something like
String[] ar = {"one", "two", "three"};
JList Jlist1 = new JList(ar);

this created a new jList instead of using my already created one, no ?

created using the Desing mode from NetBeans IDE,
  • maybe not good idea to be prisonier of code generated by

  • add a new Item to DefaultListModel

and I want to add items to that list using a secondary class which parses a big xml list and gets the data from it.

  • sounds like as you have an issue with Concurency in Swing , updates to the already visible Swing GUI must be done on EDT

  • use SwingWorker#publish() for long and hard job (which parses a big xml list and gets the data from it.)

for example, add a new Item to DefaultListModel

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Testing extends JFrame {

    private static final long serialVersionUID = 1L;
    private DefaultListModel listModel = new DefaultListModel();
    private JList list = new JList(listModel);
    private int currentSelectedRow = 0;
    private int xX = 0;

    public Testing() {
        setLocation(400, 300);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        for (int x = 0; x < 9; x++) {
            listModel.addElement("" + x);
            xX++;
        }
        JScrollPane sp = new JScrollPane(list);
        add(sp, BorderLayout.CENTER);
        JButton btn1 = new JButton("Reset Model CastingModel");
        add(btn1, BorderLayout.NORTH);
        btn1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                list.clearSelection();
                DefaultListModel model = (DefaultListModel) list.getModel();
                model.removeAllElements(); 
                // note Swing GUI by default to freeze if is removed more that 
                // 999 elemets from the JList or its underlaying XxxListModel, 
                // to use repeatly Actions from SwingTimer on short period
                for (int x = 0; x < 9; x++) {
                    model.addElement("" + (x + xX));
                    xX++;
                }
                list.setModel(model);
            }
        });

        JButton btn2 = new JButton("Reset Model directly from Model");
        add(btn2, BorderLayout.SOUTH);
        btn2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent ae) {
                list.clearSelection();
                listModel.removeAllElements();
                for (int x = 0; x < 9; x++) {
                    listModel.addElement("" + (x + xX));
                    xX++;
                }
            }
        });
        pack();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Testing().setVisible(true);
            }
        });
    }
}
String[] ar = {"one", "two", "three"};
JList Jlist1 = new JList(ar);

The constructor you are using is as follows

/**
 * Constructs a <code>JList</code> that displays the elements in
 * the specified array. This constructor creates a read-only model
 * for the given array, and then delegates to the constructor that
 * takes a {@code ListModel}.
 * <p>
 * Attempts to pass a {@code null} value to this method results in
 * undefined behavior and, most likely, exceptions. The created model
 * references the given array directly. Attempts to modify the array
 * after constructing the list results in undefined behavior.
 *
 * @param  listData  the array of Objects to be loaded into the data model,
 *                   {@code non-null}
 */
public JList(final E[] listData)
{
    this (
        new AbstractListModel<E>() {
            public int getSize() { return listData.length; }
            public E getElementAt(int i) { return listData[i]; }
        }
    );
}

So you need to have your array which you are passing as an argument to the constructor final. Also do make use of generics.

final String[] ar = {"one", "two", "three"};
JList<String> Jlist1 = new JList<String>(ar);

Lastly since you are using new keyword it is bound to create new object. Just make your original list point to this new JList object created using your array. Mind you have to make it final and cannot be changed later.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM