我正在通过JList中的鼠标事件在JTable中显示数据。我想知道在用户单击JLIst之后如何更改特定数据的字体颜色,这是照片,以实现所需的结果
list.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent arg0) {
int solutionindex =list.getSelectedIndex();
if(solutionindex==0) {
for (int i=0;i<table.getRowCount();i++) {
for (int j=0;j<table.getColumnCount();j++) {
table.setValueAt(b.charAt(i, j), i,j);
}// end of second for loop
}// end of for loop
}
else {
for (int i=0;i<table.getRowCount();i++) {
for (int j=0;j<table.getColumnCount();j++) {
table.setValueAt(solutions.get(solutionindex1).getBoard().charAt(i, j), i,j);
}// end of second for loop
}// end of for loop
}
table.setDefaultRenderer(String.class, new DefaultTableCellRenderer(){
@Override
public java.awt.Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column) {
java.awt.Component c = super.getTableCellRendererComponent(table,value,isSelected,hasFocus,row,column);
c.setForeground(Color.red);
return c;
}
});
答案 0 :(得分:1)
在ListSelectionModel
上使用MouseListener
代替JList
。 (JList
会一直使用MouseListener
来更改状态。它是在触发监听器之前还是之后发生?取决于。可能会在实现上甚至在运行时发生变化(这确实令人困惑)。
将表[模型]中的对象从Character
切换为包含文本和前景色的新类型。在表格单元格渲染器中,将单元格对象强制转换为正确的类型,并在setForeground
中使用其颜色。