我正在尝试根据列-1的单元格值更改JTable单元格的背景。
因此,如果[row,Column]处的单元格值与给定值(例如“A”,“B”)不同,则更改给定单元格的背景和[row,column + 1]处的单元格
这是我现在得到的:
我想要的是以下内容:
我使用了自定义单元格渲染,但我无法达到此要求。
这是我的代码:
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Font;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
public class TestCellRendered {
private JFrame frame;
private JTable table;
private DefaultTableModel model;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
TestCellRendered window = new TestCellRendered();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
* @throws IOException
*/
public TestCellRendered() throws IOException {
initialize();
}
/**
* Initialize the contents of the frame.
* @throws IOException
*/
private void initialize() throws IOException {
frame = new JFrame();
frame.setResizable(false);
frame.setBounds(100, 100, 975, 756);
frame.getContentPane().setLayout(null);
model = new DefaultTableModel();
model.addColumn("À remplacer");
model.addColumn("Lignes");
table = new JTable(model);
MyRenderer myRenderer = new MyRenderer(); // See below
table.setDefaultRenderer(Object.class , myRenderer);
table.setBackground(Color.LIGHT_GRAY);
Font font = new Font("",1,14);
table.setForeground(Color.black);
table.setFont(font);
//Add rows to my table
model.addRow(new Object[]{"a",""});
model.addRow(new Object[]{"b", ""});
model.addRow(new Object[]{"c", ""});
JScrollPane scrollPane = new JScrollPane(table, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
scrollPane.setBounds(66, 66, 519, 421);
frame.getContentPane().add(scrollPane);
}
class MyRenderer extends DefaultTableCellRenderer
{
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);
if (! table.isRowSelected(row))
{
if( !(value.equals("a") |value.equals("b") ))
{
c.setBackground(new java.awt.Color(231, 76, 60));
c.setForeground(new java.awt.Color(255,255,255));
}
else{
c.setBackground(table.getBackground());
c.setForeground(table.getForeground());
}
}
return c;
}
}
}
答案 0 :(得分:2)
基于列-1的单元格的值。
if( !(value.equals("a") |value.equals("b") ))
你总是在当前专栏上进行测试。您需要在第一列进行测试:
String text = table.getValueAt(row, 0).toString();
if( !(text.equals("a") |text.equals("b") ))
请注意,使用肯定测试在if语句中编写代码通常更容易:
if (text.equals("a" || text.equals("b"))
{
c.setBackground(table.getBackground());
c.setForeground(table.getForeground());
}
else
{
c.setBackground(new java.awt.Color(231, 76, 60));
c.setForeground(new java.awt.Color(255,255,255));
}