jtable.setSelectionBackground(Color.blue);
解决方案 »
- java内存开辟和回收的问题
- JFrame中的setMinimumSize和setMaxmumSize
- 大家知道在JAVA中怎么把一个组件的内容传给其它程序吗?
- 今天做JSP做的真郁闷!分不多散了!
- 继承HashSet问题
- DATE()使用的问题
- 问几道JAVA题目
- Java中怎样迅速比较两个文本文件是否完全一致?
- 紧急!为什么我的applet不能够连接oracle数据库。我用的JDBC,提示找不到JDBC类。应该如何配置服务器啊
- 32位的机器Eclipse3.2为什么安装swt运行会报错?
- The Java Programming Language,Third Edition 这本书可从什么地方下载?
- 请问invokeLater(Runnable doRun)的用法
我使用了你的建议:jtable.setSelctionBackground(Color.blue)
程序执行了这一步,却没有改变选中的一行的颜色。
但若使用jtable.setbackground(Color.blue),只是把整个table的背景都改了,这却是可以在程序中实现的。
这会是什么问题呢。是不是selectionModel的选择不行,我用的是defaultListSelectionModel.
如果是其他操作系统,setSelctionBackground也应该有效果
SwingSet2
jtable.addFocusListener( new FocusAdapter(){
public void focusGained(FocusEvent e){
table.setSelectionBackground(Color.blue);
table.setSelectionForeground(Color.white);
//....
}
public void focusLost(FocusEvent e){
table.setSelectionBackground(Color.lightGray);
table.setSelectionForeground(Color.black);
//....
}
}
);
但问题是:我在table里自己写了一个Renderer类,其中A和B两列都设了这个renderer。
A=table.getColumnModel().getColumn(4);
B=table.getColumnModel().getColumn(5);
A.setCellRenderer(new Renderer());
B.setCellRenderer(new Renderer());
我发现选中某一行后,该行中,其他的列都正常显示兰色。但A,B两列没有变化,
请问该怎么修改一下。
Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int column){
if(isSelected) {
setBackground(table.getSelectionBackground());
}
}
可还是存在问题,当我选中某行时,该行全变为了兰色背景,但是A,B两列的整列都是兰色背景,请问这是怎么回事啊
但这种方法有个缺点,就是按CTRL+C,是复制整行而不是一个单元格,要避免这个问题可以使用Renderer,见以下代码?package com.iaworld.arc.gui.components;import javax.swing.*;
import java.awt.*;/**
* User: andyhung
* Date: Nov 27, 2003
* Time: 2:40:59 PM
*/
public class DefaultCellRenderer
extends javax.swing.table.DefaultTableCellRenderer
{
public DefaultCellRenderer()
{
super();
} public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
Component p = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
if(table.getSelectedRow() == row)
p.setBackground(Color.CYAN);
else
p.setBackground(Color.WHITE);
p.setForeground(Color.BLACK);
return p;
}
}
Arrays.sort(rows);
if(isSelected && Arrays.binarySearch(rows,row)>=0){
setBackground(table.getSelectionBackground());
setForeground(table.getSelectionForeground());
}
class CellColorRenderer 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(isSelected)
c.setBackground(Color.yellow);
else
c.setBackground(Color.white);
return p;
}
}
让每一个列都加入这个绘制器
TableColumn column[]=new TableColumn[jt.getColumnModel().getColumnCount()];
for(int i = 0 ; i<jt.getColumnModel().getColumnCount();i++)
{
column[i] = jt.getColumnModel().getColumn(i);
column[i].setCellRenderer(new CellColorRenderer());
}