简体   繁体   English

为JList设置了Java DefaultListModel,但是添加对象不起作用

[英]Java DefaultListModel is set for a JList, but adding objects doesn't work

This is my code: 这是我的代码:

JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(75, 35, 352, 154);
getContentPane().add(scrollPane);
DefaultListModel<Krug> dlm = new DefaultListModel();
JList list = new JList();
scrollPane.setViewportView(list);
list.setModel(dlm); 
//using this button Object(Krug) shoul be added to dlm  
JButton btnDodaj = new JButton("Dodaj krug");
btnDodaj.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {        
        DlgKrug dijalog = new DlgKrug();
        dijalog.setVisible(true);
        //checks if OK button is pressed on dialog window
        if (dijalog.isPotvrdjen()) {        
            dlm.add(0, dijalog.k);      
        } else {}       
    }
});

The k object is created in DlgKrug(JDialog) and it's public . k对象在DlgKrug(JDialog)创建,并且是public

When I try to add an object to the list, it doesn't work and I am not getting an error message. 当我尝试将对象添加到列表时,它不起作用,并且没有收到错误消息。 DlgKrug works properly (I checked), but I think the problem occurs here. DlgKrug正常工作(我检查过),但我认为问题出在这里。

I apologize if I am not very precise, but I am just a Java beginner and this is my first stackoverflow question. 如果我不太精确,我深表歉意,但是我只是一个Java初学者,这是我的第一个stackoverflow问题。

First off, I suggest simplifying all of that to something similar to this 首先,我建议简化了这一切,以类似于此

DefaultListModel dlm = new DefaultListModel();
JList list = new JList(dlm); //Bind the dlm and JList here
JScrollPane pane = new JScrollPane(list); //Bind the list and scrollpane here

Then you can add elements to the dlm in your action listener like this 然后你就可以在你的动作监听这样的元素添加到DLM

button.addActionListener(e ->
{
    dlm.add(index, content);
    //Or use this to just add the object to the end of the list
    dlm.addElement(content);
});

You should also have a method to return what you are trying to add to the list instead of accessing it directly from the class 您还应该有一种方法来返回要添加到列表中的内容,而不是直接从类中访问它

So change this dijalog.k to a method such as: 因此,改变这种dijalog.k这样的方法:

public String getElement() //Doesn't have to be a String
{
    return someString;
}

1st you are adding empty dlm in list. 首先,您要在列表中添加空的dlm。 Then when button is pressed you are adding object to dlm... But nothing is adding to list? 然后,当按下按钮时,您正在向dlm添加对象...但是什么都没有添加到列表中? So you will get nothing. 因此,您将一无所获。

Move list.setmodel(dlm) after adding object in dlm. 在dlm中添加对象后,移动list.setmodel(dlm)。

Also use dlm.addElement not only dlm.add.. Hope that helps 不仅要使用dlm.add,还要使用dlm.addElement。希望对您有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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