【发布时间】:2012-02-09 11:33:38
【问题描述】:
我使用以下程序使用 java 类创建 JTable。如果我从选项窗格中获取 warnIcon、infoIcon 的图像,它会正确显示。但是,如果我从我的系统中添加图像,它不会显示在表格中。显示一个空白区域而不是我的图像。如何从该表中的文件(例如 A.jpg)中绘制图像?
package pointer;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import javax.swing.*;
import javax.swing.plaf.OptionPaneUI;
import javax.swing.table.*;
import sun.swing.ImageIconUIResource;
public class TableIcon1 extends JFrame {
private JTable table;
private int pHeight = 60;
public TableIcon1() {
ImageIcon testIcon = new ImageIcon("A.jpg");
// ImageIcon errorIcon = (ImageIcon) UIManager.getIcon("OptionPane.errorIcon");
ImageIcon infoIcon = (ImageIcon) UIManager.getIcon("OptionPane.informationIcon");
ImageIcon warnIcon = (ImageIcon) UIManager.getIcon("OptionPane.warningIcon");
String[] columnNames = {"Picture", "Description"};
Object[][] data = {{testIcon , "About"}, {infoIcon, "Add"}, {warnIcon, "Copy"},};
DefaultTableModel model = new DefaultTableModel(data, columnNames);
table = new JTable(model) {
@Override
public Class getColumnClass(int column) {
return getValueAt(2, column).getClass();
}
};
table.setRowHeight(pHeight);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane, BorderLayout.CENTER);
}
public static void main(String[] args) {
TableIcon1 frame = new TableIcon1();
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setLocation(150, 150);
frame.pack();
frame.setVisible(true);
}
}
【问题讨论】:
-
为什么您显示的是来自本地文件系统的
File?如果是应用资源,应该是通过URL获取的(放入Jar,添加到运行时的class-path &)。如果它是“用户资源”,则向用户提供JFileChooser,您将得到一个带有完整路径和名称的File对象。无论哪种方式都可以解决这个问题。其他几点: 1) 不要扩展JFrame。更喜欢组合而不是继承。 2) 在 EDT 上构建 GUI。 3)setLocationByPlatform(true)优于setLocation(150, 150)。 -
@AndrewThompson 如何在此示例中为 testicon 添加 JFilechooser
-
阅读How to Use File Choosers后,何不尽最大努力?如果您遇到困难,请提出具体问题。顺便说一句 - 不要以为我能读懂你的想法。您的问题是否意味着图像 不是 mKorbel 假设的应用程序资源? (通常,更多信息总比更少信息好。)
-
@javalearner : 你的图片文件夹在哪里?
-
URL url = getClass().getResource("image/Pointer.GIF"); ImageIcon testIcon = new ImageIcon(url);它工作正常
标签: java swing icons jtable imageicon