如何在 Java JList 中显示对象?

编程入门 行业动态 更新时间:2024-10-24 12:23:51
本文介绍了如何在 Java JList 中显示对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我正在尝试创建一个学生注册系统.在这个系统中,学生可以通过点击课程"按钮来查看课程名称、课程学分和课程讲师.为此,我有一个课程类、一个数据库、一个框架和一个 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屋!

更多推荐

[db:关键词]

本文发布于:2023-04-16 10:03:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/884933.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   如何在   Java   JList

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!