Java 更改 JTable 特定单元格中的字体颜色?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23814282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change the font color in a specific cell of a JTable?
提问by ConfusingCalc
Before starting, I've viewed a handful of solutions as well as documentation. I can't seem to figure out why my code isn't working the way I believe it should work. I've extended DefaultTableCellRenderer but I don't believe it is being applied - that or I messed things up somewhere.
在开始之前,我查看了一些解决方案和文档。我似乎无法弄清楚为什么我的代码没有按照我认为应该工作的方式工作。我已经扩展了 DefaultTableCellRenderer 但我不相信它正在被应用 - 或者我把事情搞砸了。
Here are the threads / websites I've looked into before posting this question:
以下是我在发布此问题之前查看过的主题/网站:
- Swing - Is it possible to set the font color of 'specific' text within a JTable cell?
- JTable Cell Renderer
- http://docs.oracle.com/javase/tutorial/uiswing/components/table.html
- Swing - 是否可以在 JTable 单元格中设置“特定”文本的字体颜色?
- JTable 单元格渲染器
- http://docs.oracle.com/javase/tutorial/uiswing/components/table.html
I realize the first link uses HTML to change the font color, but I would think the way I went about it should produce the same result.
我意识到第一个链接使用 HTML 来更改字体颜色,但我认为我的处理方式应该会产生相同的结果。
To make it easier on those who want to help me figure out the issues, I've created an SSCCE.
为了让那些想帮助我解决问题的人更容易,我创建了一个 SSCCE。
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
public class TableTest {
private static final int IMPORTANT_COLUMN = 2;
public static void createAndShowGUI() {
Object[][] data = new Object[2][4];
//create sample data
String[] realRowData = { "1", "One", "1.0.2", "compile" };
String[] fakeRowData = { "2", "Two", "1.3.2-FAKE", "compile" };
//populate sample data
for(int i = 0; i < realRowData.length; i++) {
data[0][i] = realRowData[i];
data[1][i] = fakeRowData[i];
}
//set up tableModel
JTable table = new JTable();
table.setModel(new DefaultTableModel(data,
new String[] { "ID #", "Group #", "version", "Action" })
{
Class[] types = new Class[] {
Integer.class, String.class, String.class, String.class
};
boolean[] editable = new boolean[] {
false, false, true, false
};
@Override
public Class getColumnClass(int columnIndex) {
return types[columnIndex];
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return editable[columnIndex];
}
});
//set custom renderer on table
table.setDefaultRenderer(String.class, new CustomTableRenderer());
//create frame to place table
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setMinimumSize(new Dimension(400, 400));
JScrollPane scrollPane = new JScrollPane();
scrollPane.setViewportView(table);
f.add(scrollPane);
f.pack();
f.setVisible(true);
}
//MAIN
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
//Custom DefaultTableCellRenderer
public static class CustomTableRenderer extends DefaultTableCellRenderer {
public Component getTableCellRenderer(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column)
{
Component c = super.getTableCellRendererComponent(table, value, isSelected,
hasFocus, row, column);
String versionVal = table.getValueAt(row, IMPORTANT_COLUMN).toString();
if(versionVal.contains("FAKE")) {
//set to red bold font
c.setForeground(Color.RED);
c.setFont(new Font("Dialog", Font.BOLD, 12));
} else {
//stay at default
c.setForeground(Color.BLACK);
c.setFont(new Font("Dialog", Font.PLAIN, 12));
}
return c;
}
}
}
My goal is to highlight any value in the version column that contains the word FAKE
in a red bold text.
我的目标是突出显示版本列中包含FAKE
红色粗体文本中的单词的任何值。
采纳答案by camickr
I've extended DefaultTableCellRenderer but I don't believe it is being applied
我已经扩展了 DefaultTableCellRenderer 但我不相信它正在被应用
Some simple debugging tips:
一些简单的调试技巧:
- Add a simple System.out.println(...) to the method you think should be invoked
- When overriding a method, make sure you use the
@Override
annotation (you used it in the TableModel class, but not your renderer class).
- 在您认为应该调用的方法中添加一个简单的 System.out.println(...)
- 覆盖方法时,请确保使用
@Override
注释(您在 TableModel 类中使用它,而不是在渲染器类中使用它)。
Your problem is a typing mistake because you are not overriding the proper method:
您的问题是打字错误,因为您没有覆盖正确的方法:
@Override
// public Component getTableCellRenderer(...) // this is wrong
public Component getTableCellRendererComponent(...)
The override annotation will display a compile message. Try it before changing the code.
覆盖注释将显示编译消息。在更改代码之前尝试一下。
Also, your first column is NOT an Integer class. Just because it contains String representations of an Integer does not make it an Integer. You need to add an Integer object to the model.
此外,您的第一列不是 Integer 类。仅仅因为它包含一个整数的字符串表示并不使它成为一个整数。您需要向模型添加一个 Integer 对象。
回答by jdiver
Replace your custom table cell rendere with the below.
将您的自定义表格单元格渲染替换为以下内容。
Explanations are in comments. Basically, you should override getTableCellRendererComponent
then check for correct column (there may be other methods instead of checking header value), then set cell depending on color.
解释在评论中。基本上,您应该覆盖getTableCellRendererComponent
然后检查正确的列(可能有其他方法而不是检查标题值),然后根据颜色设置单元格。
Do not forget last else block to set color to default if it is not the column you want.
如果不是您想要的列,请不要忘记最后一个 else 块将颜色设置为默认值。
//Custom DefaultTableCellRenderer
public static class CustomTableRenderer extends DefaultTableCellRenderer {
// You should override getTableCellRendererComponent
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
Component c = super.getTableCellRendererComponent(table, value, isSelected,
hasFocus, row, column);
// Check the column name, if it is "version"
if (table.getColumnName(column).compareToIgnoreCase("version") == 0) {
// You know version column includes string
String versionVal = (String) value;
if (versionVal.contains("FAKE")) {
//set to red bold font
c.setForeground(Color.RED);
c.setFont(new Font("Dialog", Font.BOLD, 12));
} else {
//stay at default
c.setForeground(Color.BLACK);
c.setFont(new Font("Dialog", Font.PLAIN, 12));
}
} else {
// Here you should also stay at default
//stay at default
c.setForeground(Color.BLACK);
c.setFont(new Font("Dialog", Font.PLAIN, 12));
}
return c;
}
}