gpt4 book ai didi

java table自定义TableCellRenderer根据单元格内容值更改行颜色

转载 作者:行者123 更新时间:2023-12-01 13:46:51 27 4
gpt4 key购买 nike

我正在开发java应用程序。我想在一个有3列名称类(class)和年份的表中显示数据。我根据互联网上的教程使用tablerenderer。这段代码实际上做的是根据青色和灰色对行进行着色到行号..但我想仅当年份列(年份值)等于某个值(假设为3)时才将青色设置为行。这意味着如果第三行年份列值等于5,则第三行颜色应为青色,否则应为青色灰色的。这是我在互联网上找到的代码..那么我如何修改它以实现我的目标??

import java.awt.Color;
import java.awt.Component;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRootPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;


public class CustomCellRenderer{
JTable table;
TableColumn tcol;
public static void main(String[] args) {
new CustomCellRenderer();
}

public CustomCellRenderer(){
JFrame frame = new JFrame("Creating a Custom Cell Reanderer!");
JPanel panel = new JPanel();
String data[][] = {{"Vinod","Computer","3"},
{"Rahul","History","2"},
{"Manoj","Biology","5"},
{"Sanjay","PSD","6"}};
String col [] = {"Name","Course","Year"};
DefaultTableModel model = new DefaultTableModel(data,col);
table = new JTable(model);
tcol = table.getColumnModel().getColumn(0);
tcol.setCellRenderer((TableCellRenderer) new CustomTableCellRenderer());
tcol = table.getColumnModel().getColumn(1);
tcol.setCellRenderer((TableCellRenderer) new CustomTableCellRenderer());
tcol = table.getColumnModel().getColumn(2);
tcol.setCellRenderer((TableCellRenderer) new CustomTableCellRenderer());
JTableHeader header = table.getTableHeader();
header.setBackground(Color.yellow);
JScrollPane pane = new JScrollPane(table);
panel.add(pane);
frame.add(panel);
frame.setSize(500,150);
frame.setUndecorated(true);
frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}

public class CustomTableCellRenderer extends DefaultTableCellRenderer{
public Component getTableCellRendererComponent (JTable table,
Object obj, boolean isSelected, boolean hasFocus, int row, int column) {
Component cell = super.getTableCellRendererComponent(
table, obj, isSelected, hasFocus, row, column);

if (isSelected) {
cell.setBackground(Color.green);
}
else {
if (row % 2 == 0 ) {
cell.setBackground(Color.cyan);
}
else {
cell.setBackground(Color.lightGray);
}
}
return cell;
}
}
}

最佳答案

but i want to set cyan color to row only if year column (value of year) equals to certain value

不要使用单独的渲染器。相反,您可以使用 Table Row Rendering 中找到的方法。 .

关于java table自定义TableCellRenderer根据单元格内容值更改行颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20303829/

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