Java JList problems

会有一股神秘感。 提交于 2019-12-13 07:43:28

问题


Ok what am trying to do is allow the user to make a list for themselves, what ever they type in in the TextField the output of that will be shown in the Jlist but my problem here is that if i type in another word to the TextField the output of that is either appending or replacing the other word that was already there it suppose to go beneath the other word and save there can anyone help me please??

    public lala(){

    b2 = new JButton("ADD");
    b2.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        model.removeAllElements();
        list1.setModel(model);

       }
    });

    b3 = new JButton("MOVE");
    b3.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
          model = new DefaultListModel<String>(); 
          model.addElement(field.getText());
          list.setModel(model);
          field.setText("");

        }
    });

    list = new JList<String>();
    list.setFixedCellHeight(10);
    list.setFixedCellWidth(10);
    list.setVisibleRowCount(10);
    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

    scroll = new JScrollPane(list);
    scroll.setPreferredSize(new Dimension(100,100));

    field = new JTextField(19);
    field.setToolTipText("Input Text Area Here");
    field.setFont(new Font("Corier",Font.BOLD,20));
    field.setBackground(Color.BLACK);
    field.setForeground(Color.RED);
    field.setDragEnabled(true);

    panel = new JPanel();
    panel.setBackground(Color.BLACK);

    panel.add(b3);
    //panel.add(b2);
    panel.add(field);
    panel.add(scroll);
    add(panel);

      } 
    }

回答1:


Your issue is that you are creating a whole new DefaultListModel on each Action in the event listener.

You need to declare a global DefaultListModel and addElement() to it as your user presses the button.

This might be able to help point you in the right direction:

public class Examples {

    private DefaultListModel modelList;
    private JList list;
    private JButton button;
    private JTextField field;

    public Examples() {
        modelList = new DefaultListModel();
        list = new JList(modelList);
        button = new JButton("Add To List");
        field = new JTextField();
        init();
    }

    private void init() {
        button.addActionListener((ActionEvent e) -> {
            modelList.addElement(field.getText());
            // !! list.setModel(modelList);
            field.setText("");
        });
    }

}

Here, we have registered our DefaultListModel as a instance field in our Examples class.

Then we register a new listener using the lambda expression, and have the modelList updated with the field's text, and set the modelList as the model for the JList.



来源:https://stackoverflow.com/questions/31094634/java-jlist-problems

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!