如何将图像插入 JTable 单元格

发布于 2024-10-16 16:36:32 字数 41 浏览 1 评论 0原文

有人可以为我指明如何将图像添加到 Java 表单元格中的正确方向吗?

Can someone point me in the right direction on how to add an image into Java Table cell.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

小红帽 2024-10-23 16:36:32

JTable 已经提供了默认的图标渲染器。您只需告诉表给定列中存储了哪些数据,以便它可以选择适当的呈现器。这是通过重写 getColumnClass(...) 方法来完成的:

import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;

public class TableIcon extends JPanel
{
    public TableIcon()
    {
        Icon aboutIcon = new ImageIcon("about16.gif");
        Icon addIcon = new ImageIcon("add16.gif");
        Icon copyIcon = new ImageIcon("copy16.gif");

        String[] columnNames = {"Picture", "Description"};
        Object[][] data =
        {
            {aboutIcon, "About"},
            {addIcon, "Add"},
            {copyIcon, "Copy"},
        };

        DefaultTableModel model = new DefaultTableModel(data, columnNames)
        {
            //  Returning the Class of each column will allow different
            //  renderers to be used based on Class
            public Class getColumnClass(int column)
            {
                return getValueAt(0, column).getClass();
            }
        };
        JTable table = new JTable( model );
        table.setPreferredScrollableViewportSize(table.getPreferredSize());

        JScrollPane scrollPane = new JScrollPane( table );
        add( scrollPane );
    }

    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame("Table Icon");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new TableIcon());
        frame.setLocationByPlatform( true );
        frame.pack();
        frame.setVisible( true );
    }

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

}

JTable already provides a default renderer for icons. You just need to tell the table what data is stored in a given column so it can choose the appropriate renderer. This is done by overriding the getColumnClass(...) method:

import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;

public class TableIcon extends JPanel
{
    public TableIcon()
    {
        Icon aboutIcon = new ImageIcon("about16.gif");
        Icon addIcon = new ImageIcon("add16.gif");
        Icon copyIcon = new ImageIcon("copy16.gif");

        String[] columnNames = {"Picture", "Description"};
        Object[][] data =
        {
            {aboutIcon, "About"},
            {addIcon, "Add"},
            {copyIcon, "Copy"},
        };

        DefaultTableModel model = new DefaultTableModel(data, columnNames)
        {
            //  Returning the Class of each column will allow different
            //  renderers to be used based on Class
            public Class getColumnClass(int column)
            {
                return getValueAt(0, column).getClass();
            }
        };
        JTable table = new JTable( model );
        table.setPreferredScrollableViewportSize(table.getPreferredSize());

        JScrollPane scrollPane = new JScrollPane( table );
        add( scrollPane );
    }

    private static void createAndShowGUI()
    {
        JFrame frame = new JFrame("Table Icon");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new TableIcon());
        frame.setLocationByPlatform( true );
        frame.pack();
        frame.setVisible( true );
    }

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

}
2024-10-23 16:36:32

要么预先创建图像图标:

ImageIcon icon = new ImageIcon("image.gif");
table.setValueAt(icon, row, column);

或者您可以尝试覆盖图标字段的渲染器:

static class IconRenderer extends DefaultTableCellRenderer {
  public IconRenderer() { super(); }

  public void setValue(Object value) {
    if (value == null) {
      setText("");
    }
    else
    {
      setIcon(value);
    }
}

Either create the imageicon up front:

ImageIcon icon = new ImageIcon("image.gif");
table.setValueAt(icon, row, column);

Or you can try overriding the renderer for your icon field:

static class IconRenderer extends DefaultTableCellRenderer {
  public IconRenderer() { super(); }

  public void setValue(Object value) {
    if (value == null) {
      setText("");
    }
    else
    {
      setIcon(value);
    }
}
在风中等你 2024-10-23 16:36:32

1-向jtable添加标签(为此创建类)

 class LabelRendar implements TableCellRenderer{

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
      //  throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        return (Component)value;
    }

}

2-编写jButton以添加图像

DefaultTableModel m = (DefaultTableModel) jTable1.getModel();
      jTable1.getColumn("image").setCellRenderer(new LabelRendar());  // call class 
      JLabel lebl=new JLabel("hello");
      lebl.setIcon(new javax.swing.ImageIcon(getClass().getResource("/main/bslogo120.png"))); // NOI18N
          m.addRow(new Object[]{"", "","",lebl});

1- add label to jtable ( create class for this)

 class LabelRendar implements TableCellRenderer{

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
      //  throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        return (Component)value;
    }

}

2- code jButton to add image

DefaultTableModel m = (DefaultTableModel) jTable1.getModel();
      jTable1.getColumn("image").setCellRenderer(new LabelRendar());  // call class 
      JLabel lebl=new JLabel("hello");
      lebl.setIcon(new javax.swing.ImageIcon(getClass().getResource("/main/bslogo120.png"))); // NOI18N
          m.addRow(new Object[]{"", "","",lebl});
青芜 2024-10-23 16:36:32

我创建了自己的类来实现 TableCellRenderer。我可以从 JLabel 扩展此类,但我更愿意保持它独立并使用 JLabel“标签”作为类组件。

public class GLabel implements TableCellRenderer{
    //The JLabel that is used to display image
    private final JLabel label = new JLabel();  
    
    /**
     * 
     * @param text
     * @param image 
     */
    public GLabel(String text, ImageIcon image) {
        label.setText(text);
        label.setIcon(image);
    }
    
    public GLabel(){}

    public JLabel getLabel() {
        return label;
    }      

    /**
     *
     * @param table the JTable that is asking the renderer to draw; can be null
     * @param value the value of the cell to be rendered. 
     * It is up to the specific renderer to interpret and draw the value. 
     * For example, if value is the string "true", it could be rendered as a string or it could be rendered as a check box that is checked. 
     * null is a valid value
     * @param isSelected true if the cell is to be rendered with the selection highlighted; otherwise false
     * @param hasFocus if true, render cell appropriately. For example, put a special border on the cell, if the cell can be edited, render in the color used to indicate editing
     * @param row the row index of the cell being drawn. When drawing the header, the value of row is -1
     * @param column the column index of the cell being drawn
     * @return 
     */
    @Override
    public Component getTableCellRendererComponent(JTable table,
                                      Object value,
                                      boolean isSelected,
                                      boolean hasFocus,
                                      int row,
                                      int column) {
        GLabel gLabel = (GLabel)value;
        return (Component) gLabel.getLabel();
    }
}

我创建了一个新的 DefaultTableModel 对象。我重写 getColumnClass() 方法以在运行时传递适当的类。

private final DefaultTableModel tblmodel = new DefaultTableModel() {        
        /**
         * This method is called by table cell renderer.
         * The method returns class of the cell data. This helps the renderer to display icons and 
         * other graphics in the table.
         */
        @Override
        public Class getColumnClass(int column)
        {
            for(int i = 0; i < tblmodel.getRowCount(); i++)
            {
                //The first valid value of a cell of given column is retrieved.
                if(getValueAt(i,column) != null)
                {
                    return getValueAt(i, column).getClass();
                }
            }
            //if no valid value is found, default renderer is returned.
            return super.getColumnClass(column);
        }
        
    };

我使用我创建的 DefaultTableModel 创建了 JTable 对象。

JTable jtable = new JTable(tblmodel);

我为 GLabel 类设置了默认渲染器,

jtable.setDefaultRenderer(GLabel.class, new GLabel());

我创建了新的 GLabel 对象。

GLabel glabel = new GLabel("testing", new ImageIcon("c://imagepath"));

最后,我使用TableModel的addRow(Object[] rowData)方法将GLabel添加到JTable中。

I created my own class that implements TableCellRenderer. I can extend this class from JLabel, but I have preferred to keep it independent and used JLabel 'label' as a class component.

public class GLabel implements TableCellRenderer{
    //The JLabel that is used to display image
    private final JLabel label = new JLabel();  
    
    /**
     * 
     * @param text
     * @param image 
     */
    public GLabel(String text, ImageIcon image) {
        label.setText(text);
        label.setIcon(image);
    }
    
    public GLabel(){}

    public JLabel getLabel() {
        return label;
    }      

    /**
     *
     * @param table the JTable that is asking the renderer to draw; can be null
     * @param value the value of the cell to be rendered. 
     * It is up to the specific renderer to interpret and draw the value. 
     * For example, if value is the string "true", it could be rendered as a string or it could be rendered as a check box that is checked. 
     * null is a valid value
     * @param isSelected true if the cell is to be rendered with the selection highlighted; otherwise false
     * @param hasFocus if true, render cell appropriately. For example, put a special border on the cell, if the cell can be edited, render in the color used to indicate editing
     * @param row the row index of the cell being drawn. When drawing the header, the value of row is -1
     * @param column the column index of the cell being drawn
     * @return 
     */
    @Override
    public Component getTableCellRendererComponent(JTable table,
                                      Object value,
                                      boolean isSelected,
                                      boolean hasFocus,
                                      int row,
                                      int column) {
        GLabel gLabel = (GLabel)value;
        return (Component) gLabel.getLabel();
    }
}

I created a new DefaultTableModel object. I overrides getColumnClass() method to pass appropriate Class at runtime.

private final DefaultTableModel tblmodel = new DefaultTableModel() {        
        /**
         * This method is called by table cell renderer.
         * The method returns class of the cell data. This helps the renderer to display icons and 
         * other graphics in the table.
         */
        @Override
        public Class getColumnClass(int column)
        {
            for(int i = 0; i < tblmodel.getRowCount(); i++)
            {
                //The first valid value of a cell of given column is retrieved.
                if(getValueAt(i,column) != null)
                {
                    return getValueAt(i, column).getClass();
                }
            }
            //if no valid value is found, default renderer is returned.
            return super.getColumnClass(column);
        }
        
    };

I created JTable object using DefaultTableModel I created.

JTable jtable = new JTable(tblmodel);

I set default renderer for GLabel class

jtable.setDefaultRenderer(GLabel.class, new GLabel());

I created new GLabel object.

GLabel glabel = new GLabel("testing", new ImageIcon("c://imagepath"));

Finally, I used addRow(Object[] rowData) method of TableModel to add GLabel to the JTable.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文