简体   繁体   English

无法添加到我的JList?

[英]Can't add to my JList?

I've a class called PlaceCategory, which have a name and a color. 我有一个名为PlaceCategory的类,它具有名称和颜色。 And when I want to create a new PlaceCategory I first enter the name of it and then choose a color. 当我想创建一个新的PlaceCategory时,我首先输入它的名称,然后选择一种颜色。 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 完成后,我用这些设置创建了一个新对象,然后将其添加到我的JList中,但是它不起作用,我收到此错误“容器类型中的方法add(Component)不适用对于参数(PlaceCategory)”,这是我的代码

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 这是我的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: 这是我的PlaceCategory类:

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. 使用add(Component)方法,您尝试添加一个新的(图形)组件。 This method is usefull if you have a JPanel. 如果您具有JPanel,则此方法很有用。 But you want to add a new list element to your JList. 但是您想向您的JList添加一个新的列表元素。

You have to understand how to work with models in Swing. 您必须了解如何在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. 在提供的程序中使用用于新JList的构造函数,您可以构造一个不可修改的模型。 Meaning you cannot add new elements. 意味着您不能添加新元素。

You have to set a model to the JList that has a method like addElement. 您必须为具有诸如addElement之类的方法的JList设置模型。 Lucky for you Swing provides such a model. Swing提供了这样的模型。 It's named DefaultListModel. 它名为DefaultListModel。 I think these are the key points to make it work. 我认为这些是使其发挥作用的关键点。

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

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