简体   繁体   中英

Can't add to my JList?

I've a class called PlaceCategory, which have a name and a color. And when I want to create a new PlaceCategory I first enter the name of it and then choose a color. They are saved to a String and a Color. And when I'm done I create a new object with those settings and then I want to add it to my JList, but it ain't working, I get this error "The method add(Component) in the type Container is not applicable for the arguments (PlaceCategory)" here is my code

class NewCatLis implements ActionListener{
public void actionPerformed(ActionEvent ave){
    String categoryName;
    Color color = Color.BLACK;

    categoryName = JOptionPane.showInputDialog(MapProgram.this, "Name on category");
    color = JColorChooser.showDialog(MapProgram.this,"Chooser color", color);
    PlaceCategory pc = new PlaceCategory(categoryName, color);
    categoryList.add(pc);


}

}

and here is my JList

private JList<PlaceCategory> categoryList;

MapProgram(){
super("map");

PlaceCategory[] category = {new PlaceCategory("Tunnelbana", Color.GREEN)};

categoryList = new JList<PlaceCategory>(category);
categoryList.setVisibleRowCount(3);
categoryList.setFixedCellWidth(50);
east.add(new JScrollPane(categoryList));
categoryList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

and here is my PlaceCategory class:

import java.awt.*;

public class PlaceCategory {

private String name;
public Color color;



public PlaceCategory(String name, Color color){
    this.name = name;
    this.color = color;


}

public String toString(){
    return name;
}

public Color getColor() {

    return color;
}


}

With the add(Component) method you try to add a new (graphical) component. This method is usefull if you have a JPanel. But you want to add a new list element to your JList.

You have to understand how to work with models in Swing. They represent the data of your Components. With your constructor used for the new JList in the provided program you construct a non modifiable model. Meaning you cannot add new elements.

You have to set a model to the JList that has a method like addElement. Lucky for you Swing provides such a model. It's named DefaultListModel. I think these are the key points to make it 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