gpt4 book ai didi

java - 如何在java中使用DefaultTableCellRenderer将图像插入到列表中

转载 作者:行者123 更新时间:2023-11-30 02:43:17 24 4
gpt4 key购买 nike

我编写此代码用于将图像插入到列中

LessonTable.setDefaultRenderer(Object.class, new SimpleTableCellRenderer());

class SimpleTableCellRenderer extends DefaultTableCellRenderer {

ImageIcon image = new ImageIcon(getClass().getResource("imagefolder/this.png"));
JLabel lbl = new JLabel();

@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {

lbl = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);

if (column == 1) {// i want to set image only for this column
lbl.setHorizontalAlignment(SwingConstants.LEFT);
lbl.setIcon(image);
}
else {
lbl.setHorizontalAlignment(SwingConstants.CENTER);
}

return lbl;

}
}

但是此代码会为除第二列之外的所有列插入图像。这里出了什么问题?

最佳答案

不要创建自定义渲染器。 JTable 已经支持图标渲染器。

相反,您需要做的是重写表模型的 getColumnClass(...) 方法以返回 Icon.class 并且表将使用正确的渲染器.

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();
}
});
}

}

关于java - 如何在java中使用DefaultTableCellRenderer将图像插入到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41004466/

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