简体   繁体   中英

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 .

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.

I apologize if I am not very precise, but I am just a Java beginner and this is my first stackoverflow question.

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

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:

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

1st you are adding empty dlm in list. Then when button is pressed you are adding object to dlm... But nothing is adding to list? So you will get nothing.

Move list.setmodel(dlm) after adding object in dlm.

Also use dlm.addElement not only dlm.add.. Hope that helps

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