is Jlist Override the List automatic? (bug)?

前端 未结 1 1229
眼角桃花
眼角桃花 2021-01-29 07:12

I hope I will get help, I will ask as general question:

I am using a JList, and due to the JList not have a (value,text) (so I can display te

相关标签:
1条回答
  • 2021-01-29 07:42

    I am using a JList, and due to the JList not have a (value,text) (so I can display text and use the value in my code)

    It's really hard to understand your problem, but I "suspect" for the quoted line that you have a missunderstanding between JList model and text displayed by the JList itself. I think that's why you have a separate List.

    The model can contain any object you want and the JList can also display a text as you want regardless the object itself. This last task is done by a ListCellRenderer. Take a look to Writing a Custom Cell Renderer

    For instance you can have this class:

    class Person {    
        String lastName;
        String name;
    
        public Person(String lastName, String name){
            this.lastName = lastName;
            this.name = name;
        }
    
        public String getLastName(){
            return this.lastName;
        }
    
        public String getName(){
            return this.name;
        }
    }
    

    Now you want your JList keep Person objects to work with them later. This part is easy just create a ListModel and add elements into it:

    DefaultListModel model = new DefaultListModel();
    model.addElement(new Person("Lennon","John"));
    model.addElement(new Person("Harrison","George"));
    model.addElement(new Person("McCartney","Paul"));
    model.addElement(new Person("Starr","Ringo"));
    

    But you want to display the name and last name of each Person. Well you can implement your own ListCellRenderer to do this:

    JList list = new JList(model);
    list.setCellRenderer(new DefaultListCellRenderer(){
        @Override
        public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
            if(value instanceof Person){
                Person person = (Person)value;
                setText(person.getName() + " " + person.getLastName());
            }
            return this;
        }
    });
    

    And your JList will show the items as you want:

    enter image description here

    0 讨论(0)
提交回复
热议问题