在不同的行中将图标添加到 jTable

Adding icons to jTable in different rows

我创建了一个 jTable 来显示国家名称和名称旁边的单元格中的国旗图标。如何使用 ImageIcon 类在同一列但不同的行中显示每个图标,而不是只显示一个字符串?

下面是我为在 jTable 的某个地方显示法国国旗图标而编写的,但它只显示字符串

    ImageIcon icon = new ImageIcon("http://www.stoma.fr/assets/images/French_Flag_Small_Icon.jpg");
    jTable.setValueAt(icon, 1, 2);

只需确保 table 模型的 getColumnClass(...) 方法中的图标列 returns Icon.class 即可轻松解决。幸运的是,如果您这样做,JTables 知道如何显示图标而无需任何额外工作。 For example.

从那里对我的代码进行的修改使用了这个 table 模型:

  DefaultTableModel model = new DefaultTableModel(COL_NAMES, 0) {
     @Override
     public Class<?> getColumnClass(int column) {
        if (getRowCount() > 0) {
           Object value = getValueAt(0, column);
           if (value != null) {
              return getValueAt(0, column).getClass(); 
           }
        }

        return super.getColumnClass(column);
     }
  };

整个程序:

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class ImageColumnTest2 {
   public static final String IMAGE_SHEET_PATH = "http://speckycdn.sdm.netdna-cdn.com/"
         + "wp-content/uploads/2010/08/flag_icons_04.jpg";
   public static final String[] COUNTRIES = {
      "Denmark", "China", "Chile", "Canada", "Belgium", "Austria",
      "Argentina", "France", "Malaysina", "Lebanon", "Korea", "Japan",
      "Italy", "Ireland", "India", "Hong Kong", "Greece", "Germany"
   };
   public static final int COLS = 6;
   public static final int ROWS = 3;
   private static final String[] COL_NAMES = {"Country", "Flag"};

   private JTable table = new JTable();
   private JScrollPane mainPane = new JScrollPane(table);

   public ImageColumnTest2() throws IOException {
      DefaultTableModel model = new DefaultTableModel(COL_NAMES, 0) {
         @Override
         public Class<?> getColumnClass(int column) {
            if (getRowCount() > 0) {
               Object value = getValueAt(0, column);
               if (value != null) {
                  return getValueAt(0, column).getClass();
               }
            }

            return super.getColumnClass(column);
         }
      };
      URL url = new URL(IMAGE_SHEET_PATH);
      BufferedImage img = ImageIO.read(url);
      int x1 = 15;  // sorry about the magic numbers
      img = img.getSubimage(x1, 0, img.getWidth() - 2 * x1, img.getHeight());

      int y1 = 20 ;  // ditto!
      int w = img.getWidth() / COLS;
      int h = img.getHeight() / ROWS;
      for (int row = 0; row < ROWS; row++) {
         int y = (row * img.getHeight()) / ROWS;
         for (int col = 0; col < COLS; col++) {
            int x = (col * img.getWidth()) / COLS;
            BufferedImage subImg = img.getSubimage(x, y, w, h);

            subImg = subImg.getSubimage(x1, 0, subImg.getWidth() - 2 * x1, subImg.getHeight() - y1);

            ImageIcon icon = new ImageIcon(subImg);
            String country = COUNTRIES[col + row * COLS];
            Object[] rowData = {country, icon};
            model.addRow(rowData);
         }
      }


      table.setModel(model);
      table.setRowHeight(((ImageIcon)model.getValueAt(0, 1)).getIconHeight());
   }

   public JComponent getMainComponent() {
      return mainPane;
   }

   private static void createAndShowGui() {
      ImageColumnTest2 imgColumnTest = null;
      try {
         imgColumnTest = new ImageColumnTest2();
      } catch (MalformedURLException e) {
         e.printStackTrace();
         System.exit(-1);
      } catch (IOException e) {
         e.printStackTrace();
         System.exit(-1);
      }

      JFrame frame = new JFrame("ImageColumnTest");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(imgColumnTest.getMainComponent());
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

显示为: