如何在 Java JList 中显示对象? [英] How To Display Objects in Java JList?

查看:24
本文介绍了如何在 Java JList 中显示对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个学生注册系统.在这个系统中,学生可以通过点击课程"按钮来查看课程名称、课程学分和课程讲师.为此,我有一个课程类、一个数据库、一个框架和一个 JList 课程列表.

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.

现在,我的问题是在我的框架中,JList 总是看起来像 p1.Courses@4532当我不小心尝试使用 System.out.println() 打印对象时,我看到了类似的问题.但在这种情况下,我将数组列表转换为数组,而我的 JList 保存对象(JList).所以如果你帮助我,我会很高兴.

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.

推荐答案

你需要在 Course 类中重写 toString(),这样它就会返回你想要显示的课程名称.

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

看看这个例子:

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;
    }
}

这将显示以下内容:

这篇关于如何在 Java JList 中显示对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆