gpt4 book ai didi

java - 自定义 DefaultTableCellRenderer 不更改 jTable 上行的背景颜色

转载 作者:行者123 更新时间:2023-12-01 17:56:11 25 4
gpt4 key购买 nike

我正在尝试从 ArrayList 填充我的表格,并使用自定义的 DefaultTableCellRenderer 来渲染它:

public class CustomRender extends DefaultTableCellRenderer {
private ArrayList<Color> desiredColors = new ArrayList<Color>();

public void setColors(Color incomingColor)
{
desiredColors.add(incomingColor);
}

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
Component cellComponent = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
for (int i = 0; i < desiredColors.size(); i++) {
cellComponent.setBackground(desiredColors.get(i));
}
return cellComponent;
}
}

我就是这样使用的

CustomRender colouringTable = new CustomRender();

DefaultTableModel model = new DefaultTableModel(){
public boolean isCellEditable(int rowIndex, int mColIndex) {
return false;
}
};

table = new JTable(model);
JScrollPane scroller = new JScrollPane(table);

model.addColumn("ID");
model.addColumn("Username");
model.addColumn("Departement");

for (Employee e: Departement.employees) {
model.addRow(new Object[]{String.valueOf(e.userId), e.username, e.departement});
if (e.chef) {
colouringTable.setColors(Color.RED);
} else {
colouringTable.setColors(Color.GREEN);
}
}

for (int i = 0; i < table.getColumnCount(); i++) {
table.getColumnModel().getColumn(i).setCellRenderer(colouringTable);
}

但由于某种原因,没有任何行是红色或绿色的,它没有改变任何颜色。谁能指出我做错了什么?

最佳答案

您没有正确使用单元格渲染器。目前,您的代码在填充 JTable 模型时用颜色填充 ArrayList、desiredColors,然后在渲染器中迭代该列表,但这根本没有意义,因为所有单元格都将简单地被赋予由数组列表。

相反,您想要做的是为渲染器提供两种颜色(可能在其构造函数中),并在渲染器的 getTableCellRendererComponent 方法中,测试表中的数据(由 获取) value 参数,并使用该信息来设置渲染器的颜色。

例如,

class MyRenderer extends DefaultTableCellRenderer {
private Color chefColor;
private Color defaultColor;

public MyRenderer(Color chefColor, Color defaultColor) {
this.chefColor = chefColor;
this.defaultColor = defaultColor;
setOpaque(true);
}

@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
Component superComp = super.getTableCellRendererComponent(table, value, isSelected,
hasFocus, row, column);

// here test if row holds a chef item
// if so, set background color to chefColor
// otherwise set background color to the defaultColor.
return superComp;
}
}
<小时/>

例如:

import java.awt.Color;
import java.awt.Component;

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

/**
* Example of using a DefaultTableModel that holds a row of specific type
* Example of hidden column determining color of cells
* @author Pete
*
*/
@SuppressWarnings("serial")
public class SimpleTableExampe extends JPanel {
RestaurantEmployee[] employees = {
new RestaurantEmployee("John", true, 1),
new RestaurantEmployee("Bill", false, 2),
new RestaurantEmployee("Sally", true, 3),
new RestaurantEmployee("Frank", false, 4),
new RestaurantEmployee("Jim", false, 5),
new RestaurantEmployee("Imelda", true, 6)
};
private MyTableModel tableModel = new MyTableModel();
private JTable table = new JTable(tableModel);

public SimpleTableExampe() {
MyRenderer renderer = new MyRenderer(Color.RED, Color.GREEN);
for (int i = 0; i < table.getColumnCount(); i++) {
table.getColumnModel().getColumn(i).setCellRenderer(renderer);
}
add(new JScrollPane(table));
for (RestaurantEmployee employee : employees) {
tableModel.addEmployee(employee);
}
}

private static void createAndShowGui() {
SimpleTableExampe mainPanel = new SimpleTableExampe();

JFrame frame = new JFrame("SimpleTableExampe");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public static void main(String[] args) {
SwingUtilities.invokeLater(() -> createAndShowGui());
}
}

class RestaurantEmployee {
private String name;
private boolean chef;
private int id;

public RestaurantEmployee(String name, boolean chef, int id) {
this.name = name;
this.chef = chef;
this.id = id;
}

public String getName() {
return name;
}

public boolean isChef() {
return chef;
}

public int getId() {
return id;
}

@Override
public String toString() {
return "RestaurantEmployee [name=" + name + ", chef=" + chef + ", id=" + id + "]";
}
}

@SuppressWarnings("serial")
class MyTableModel extends DefaultTableModel {
private static final String[] COLUMN_NAMES = { "Name", "ID" };

public MyTableModel() {
super(COLUMN_NAMES, 0);
}

public void addEmployee(RestaurantEmployee employee) {
addRow(new RestaurantEmployee[] { employee });
}

@Override
public int getColumnCount() {
return COLUMN_NAMES.length;
}

@Override
public Class<?> getColumnClass(int columnIndex) {
if (getRowCount() > 0) {
return getValueAt(0, columnIndex).getClass();
} else {
return super.getColumnClass(columnIndex);
}
}

public RestaurantEmployee getEmployee(int row) {
return (RestaurantEmployee) super.getValueAt(row, 0);
}

@Override
public Object getValueAt(int row, int column) {
RestaurantEmployee employee = (RestaurantEmployee) super.getValueAt(row, 0);
switch (column) {
case 0:
return employee.getName();
case 1:
return employee.getId();
default:
return null;
}
}

@Override
public boolean isCellEditable(int row, int column) {
return false;
}

}

@SuppressWarnings("serial")
class MyRenderer extends DefaultTableCellRenderer {
private static final int ALPHA = 60;
private Color chefColor;
private Color defaultColor;

public MyRenderer(Color chefColor, Color defaultColor) {
this.chefColor = chefColor;
this.defaultColor = defaultColor;
setOpaque(true);
setHorizontalAlignment(SwingConstants.CENTER);
}

@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
Component superComp = super.getTableCellRendererComponent(table, value, isSelected,
hasFocus, row, column);
if (value != null) {
MyTableModel tableModel = (MyTableModel) table.getModel();
boolean chef = tableModel.getEmployee(row).isChef();
Color c = chef ? chefColor : defaultColor;
if (!hasFocus && !isSelected) {
c = new Color(c.getRed(), c.getGreen(), c.getBlue(), ALPHA);
}

superComp.setBackground(c);
}
return superComp;
}
}

关于java - 自定义 DefaultTableCellRenderer 不更改 jTable 上行的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44599900/

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