gpt4 book ai didi

java - 在 GUI 中显示对象数组

转载 作者:行者123 更新时间:2023-12-01 18:32:37 26 4
gpt4 key购买 nike

我正在开发一个程序,该程序应该跟踪蓝光电影的库存。我将电影存储在一个对象数组中(该数组存储每部电影的名称、ID、光盘数量和价格)。我知道 ArrayList 是一种在数组中存储对象的更有效方法,但出于此分配的目的,我需要使用数组。我之前已经将此程序打印到控制台,没有问题,但我正在尝试将此程序添加到 GUI。我已经为 GUI 编写了一个类,但我不知道如何将数组添加到 JPanel 和 JFrame。

这是我的 GUI 类:

class TextInFrame extends JFrame {

private JLabel greeting;
private JLabel inventoryUnsorted;
private JPanel panel;

public TextInFrame(){
super("Blu-ray Movie Inventory");
setLayout(new FlowLayout());
JFrame.setDefaultLookAndFeelDecorated(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
pack();
setVisible(true);

panel = new JPanel();
greeting = new JLabel(BluRay.programGreeting());
add(greeting);
greeting.setVerticalTextPosition(JLabel.BOTTOM);
greeting.setHorizontalTextPosition(JLabel.CENTER);
panel.add(greeting);
this.add(panel);
}
}

这是我的主要方法的一部分

public class Inventory {

public static void main(String[] args) {

TextInFrame window = new TextInFrame();
window.setSize(600, 600);

BluRay[] movies = new BluRay[5];

movies[0] = new BluRay("Man of Steel", "48461", 24, 17.99);
movies[1] = new BluRay("Fast Five", "84624", 10, 12.99);
movies[2] = new BluRay("Batman Begins", "15483", 19, 13.98);
movies[3] = new BluRay("X-Men", "48973", 6, 15.99);
movies[4] = new BluRay("The Outsiders", "01893", 16, 9.98);

String[] stringArray = Arrays.copyOf(movies, movies.length, String[].class);


// loop to print through the BluRay movies array
for (String string : stringArray) {
System.out.println(string);
}

每次我尝试将数组添加到 JLabel 或 JPanel 中时,都会收到错误“BluRay[] 无法转换为字符串”。我完全不知道如何在 GUI 中获取这些信息。我在 JPanel 中的问候语方面也遇到了麻烦。调整 JFrame 大小时它不会换行。难住了。

最佳答案

看看How to Use Lists ,它们将允许您在 GUI 上的列表中显示任意对象

查看Creating a ModelWriting a Custom Cell Renderer特别是

JLabel默认情况下不包装其内容。您可以使用 JTextArea设置为不可编辑并修改背景颜色和边框或简单地将 JLabel 的文本换行在<HTML>标签...给我们添加一个不同的布局管理器;)

对于example

关于java - 在 GUI 中显示对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23463522/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com