How To Display Objects in Java JList?

后端 未结 1 414
感情败类
感情败类 2021-01-29 15:29

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\" bu

相关标签:
1条回答
  • 2021-01-29 16:18

    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:

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