gpt4 book ai didi

java - setSelectionBackGround() 不设置自定义渲染单元格的颜色

转载 作者:行者123 更新时间:2023-12-01 18:49:36 25 4
gpt4 key购买 nike

我正在使用自定义 CellRenderer(TableCellRenderer 的一个实例)来呈现如下所示的 CLOSE 列的单元格。我已经为表格的 setSelectionBackGround 设置了颜色,但是选择该列的背景颜色的单元格时不会绘制。请向我提供任何见解,我将非常感激。

enter image description here

这是我的 TablecellRenderer 类

class LabelRenderer extends JLabel implements TableCellRenderer {

Font f;
Color selectionBG;
Color upDirection;

LabelRenderer(){
super();
f=new java.awt.Font("Trebuchet MS", 0, 12);
selectionBG = new java.awt.Color(204, 255, 255);
upDirection= new Color(0,102,0);
}


@Override
public Component getTableCellRendererComponent( JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
//structure of passing array (value)
// new Object[]{boolean direction, String close (change%)}

Object arr[] = (Object[])value;

Boolean direction = (Boolean)arr[0];

if( direction )
this.setForeground(upDirection);//GREEN
else
this.setForeground(Color.red);

this.setText(arr[1].toString());
this.setFont(f);


return this;
}

}

最佳答案

您的渲染器扩展了默认情况下不是不透明的JLabel。您可以在渲染器中执行setOpaque(true)。或者,您也可以扩展默认情况下不透明的 DefaultTableCellRenderer。例如:

enter image description here

import java.awt.Color;
import java.awt.Component;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;

public class TableBgDemo {
private static void createAndShowGUI() {
JFrame frame = new JFrame("TableDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Object[][] rows = { { "Column 1", "Column 2" },
{ "Column 1", "Column 2" }, { "Column 1", "Column 2" },
{ "Column 1", "Column 2" } };

Object[] columns = { "Column 1", "Column 2" };

DefaultTableModel model = new DefaultTableModel(rows, columns);

JTable table = new JTable(model);
table.getColumnModel().getColumn(0).setCellRenderer(new MyRenderer());
table.setSelectionBackground(Color.CYAN);
frame.add(new JScrollPane(table));
frame.pack();
frame.setVisible(true);
}

static public class MyRenderer extends DefaultTableCellRenderer {
@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);
c.setForeground(Color.RED);
return c;
}
}

public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

关于java - setSelectionBackGround() 不设置自定义渲染单元格的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16254640/

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