gpt4 book ai didi

java - 格式化 JTextPane

转载 作者:行者123 更新时间:2023-11-30 06:22:01 30 4
gpt4 key购买 nike

我试图让 JFrame 看起来漂亮,但我无法让它看起来漂亮。

我有以下代码

import javax.swing.*;

public class ReportGUI {
private JFrame mainFrame;
private JTextPane report;

public static Product[] products = {
new Product("Guardians of the Galaxy Vol. 2", "CD123455", 28), new Product("Kingsman 2: The Golden Circle", "CD545155", 13), new Product("Cars 3", "CD425245", 24), new Product("The Polar Express", "CD252454", 14), new Product("Harry Potter", "CD452412", 23)
};

public ReportGUI() {
prepareGUI();
}

public void prepareGUI() {
mainFrame = new JFrame("Report All Products");
mainFrame.setSize(800, 500);
report = new JTextPane();
String txt = String.format("%50s%50s%5s\n", "Product Name", "Serial Number", "Price");
for (Product product : products) {
txt += String.format("%50s\t%50s\t$%10.2f\n", product.getName().trim(), product.getSerial().trim(), product.getPrice());
}
report.setText(txt);
mainFrame.add(report);
mainFrame.setVisible(true);
}

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

这是 Product.java

public class Product() {
private String name, serial;
private double price;

public Product(String name, String serial, double price) {
this.name = name;
this.serial = serial;
this.price = price;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getSerial() {
return serial;
}

public void setSerial(String serial) {
this.serial = serial;
}

public double getPrice() {
return price;
}

public void setPrice(float price) {
this.price = price;
}

@Override
public String toString() {
return "Product{" +
"name='" + name + '\'' +
", serial='" + serial + '\'' +
", price=" + price +
'}';
}
}

我想要看起来像一张漂亮的 table 。

我怎样才能让它发挥作用?几个小时以来我一直试图让这个看起来不错,但我无法弄清楚。

任何帮助都会很棒。

最佳答案

使用Jtable相反。

public void prepareGUI() {
mainFrame = new JFrame("Report All Products");
mainFrame.setSize(800, 500);

// create column names
String[] columnNames = {"Product Name", "Serial Number", "Price"};

// create data
Object[][] data = new Object[products.length][];
for (int x = 0; x < products.length; x++){
Product product = products[x];
data[x] = new Object[]{product.getName(), product.getSerial(), product.getPrice()};
}

// initialize jtable with data and columnNames
JTable table = new JTable(data, columnNames);

// attach table to scrollpane
JScrollPane scrollPane = new JScrollPane(table);
table.setFillsViewportHeight(true);

// add scrollpane to frame
mainFrame.add(scrollPane);
mainFrame.setVisible(true);
}

关于java - 格式化 JTextPane,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47933393/

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