How To Display Objects in Java JList?

强颜欢笑 提交于 2020-07-16 10:54:01

问题


I'm trying to create a student registration system. In this system, students can see course name, course credit, and the instructor of the course by clicking the "Courses" button.For this purpose i have a Courses class, a database, a frame and a JList courslist.

ArrayList<Courses> aq = Database.allCourses(); 

//allCourses() is a static method in my Database class that returns fields from my Database as an ArrayList<Courses>

 courselist.setListData(Driver.converToCoursesArray(aq));

//Driver.converttoCoursesArray() is a static method in my Driver class that takes a ArrayList<Courses> as a paramater and returns a Courses[] array.

Now, my problem is that in my frame, JList always seen like p1.Courses@4532 I've seen a similar problem when i was accidently trying to print an object with System.out.println(). But in this situation i convert the arraylist to an array and my JList holds objects(JList). So i'll be happy if you help me.


回答1:


You need to override toString() in the Course class, such that it returns the name of the course you want to display.

Take a look at this example:

import javax.swing.*;
import java.awt.*;

public final class Example extends JFrame {

    public Example() {

        Course[] courses = {
                new Course("Course 1"),
                new Course("Course 2"),
                new Course("Course 3")
        };

        JList<Course> courseJList = new JList<>(courses);

        getContentPane().add(courseJList);

        pack();
        setMinimumSize(new Dimension(200, 200));
        setVisible(true);
    }

    public static void main(String[] args) {
        new Example();
    }
}

final class Course {

    private final String courseName;

    public Course(final String courseName) {
        this.courseName = courseName;
    }

    @Override
    public String toString() {
        return courseName;
    }
}

This displays the following:



来源:https://stackoverflow.com/questions/37596978/how-to-display-objects-in-java-jlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!