简体   繁体   中英

How to make changes to model show in JList

I'm trying to create a simple program that takes input in a JTextArea and then places it in a JList (when enter is pressed with JTextArea focused). The problem is that while the text gets saved in the ArrayList in the Model class, it isn't visible in the JList. A fix would be greatly appreciated.

Main class:

 public class Main {

  public static void main(String[] args) {

      Model model = new Model();
      JFrame frame = new JFrame();
      JPanel panel = new JPanel(new BorderLayout());
      JTextField text = new JTextField();
      JList list = new JList(model);
      JScrollPane scroll = new JScrollPane(list);

      frame.setSize(300, 300);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setLocationRelativeTo(null);

      frame.add(panel);
      panel.add(scroll, BorderLayout.CENTER);
      panel.add(text, BorderLayout.PAGE_END);

      text.setText("Enter Text");

      frame.setVisible(true);

      text.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            model.add(text.getText());
        }
    });

Model class:

public class Model extends AbstractListModel{

    List<String> list = new ArrayList<>();

    @Override
    public int getSize() {
        return list.size();
    }

    @Override
    public Object getElementAt(int index) {
        return list.get(index);
    }

    @Override
    public void addListDataListener(ListDataListener l) { }

    @Override
    public void removeListDataListener(ListDataListener l) { }

    public void add(String x){
        int size = list.size();
        list.add(size, x);
        fireIntervalAdded(this, size, size);
    }

     void remove(int index) {
        list.remove(index);
        fireIntervalRemoved(this, index, index);
    }

I've heard that using the fireIntervalAdded and fireIntervalRemoved methods would fix my issue, but that's not the case. Maybe I'm not using them properly?

You're shooting yourself in the foot with this code:

@Override
public void addListDataListener(ListDataListener l) { }

@Override
public void removeListDataListener(ListDataListener l) { }

AbstractListModel already has these methods, and by overriding them, you're preventing the view (your JList) from listening to and responding to changes in the model. Delete these empty methods, or call the super's method from within them, and your code should work.

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