2012-02-09 113 views
2

我使用以下程序来创建使用java类的JTable。如果我得到warnIcon的图像,则选项面板中的infoIcon会正确显示。但是,如果我从我的系统添加图像,它不会显示在表格中。显示一个空白区域而不是我的图像。如何从该表格中的文件(例如A.jpg)中绘制图像?JTable单元格中的图像显示

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); 
    } 
} 
+0

***为什么***是从本地文件系统显示“文件”?如果它是一个应用程序资源,它应该(通过Jar添加到运行时类路径中)通过URL获得。如果它是一个'用户资源',为用户提供一个'JFileChooser',你将得到一个带有完整路径和名称的'File'对象。无论哪种方式都可以解决这个问题。其他要点:1)不要扩展'JFrame'。比继承更喜欢构图。 2)在EDT上构建GUI。 3)'setLocationByPlatform(true)'比'setLocation(150,150)'更好。 – 2012-02-09 11:40:44

+0

@AndrewThompson如何在此示例中为testicon添加JFilechooser – javalearner 2012-02-09 11:44:07

+0

为什么在阅读完[如何使用文件选择器]后,为什么不给它最好的尝试(http://docs.oracle.com/javase/tutorial/uiswing/components /filechooser.html)?如果您遇到问题,请提出具体问题。顺便说一句 - 不要以为我能读懂你的想法。你的问题是否意味着mKorbel设想的图像是***不是应用程序资源? (通常情况下,更多信息总是比较少。) – 2012-02-09 11:48:06

回答

3
ImageIcon testIcon = new ImageIcon("A.jpg"); is road to nowhere 

图标是常见的,从来没有返回错误的路径或空值的任何异常,你必须测试回回那

最好的办法是在你的Java project创建名称icons一个新的文件夹有复制您A.jpg Icon

,那么你只能叫

URL url = ClassLoader.getSystemClassLoader().getResource("icons/A.jpg"); 
ImageIcon testIcon = new ImageIcon(url); 
+0

当我使用像这样我有空指针异常 – javalearner 2012-02-09 11:47:39

+0

-1我_knew_糟糕的systemClassLoader会再次冒泡 - 很有可能它会_you_ ;-) – kleopatra 2012-02-09 11:49:53

+0

URL url = ClassLoader.getSystemClassLoader()。的getResource( “图标/ A.JPG”); ImageIcon testIcon = new ImageIcon(url);我有空指针异常,如何解决这个问题? – javalearner 2012-02-09 11:59:44

相关问题