我有一个简单的 JTable,它显示数据和不同的背景颜色。显示数据和着色行与 DefaultTableModel 配合得很好。但是,如果我在行中添加 MouseListener 以在单击行时加载某些内容,则背景颜色会消失。如果我标记几行也是一样。我根本不需要标记行,我只需要颜色也保持不变并且 MouseEvent 可以工作。这里是相关代码:
testcase_table = new JTable() {
public Component prepareRenderer(TableCellRenderer renderer,
int row, int column) {
List<Element> cases = element.getChildren();
int passed = 0;
Component c = super.prepareRenderer(renderer, row, column);
if (!isRowSelected(row)) {
c.setBackground(getBackground());
passed = 0;
if (row <= running_testcase) {
List<Element> teststeps = cases.get(row).getChildren();
for (Element teststep : teststeps) {
if (teststep.getAttribute("status") != null
&& teststep.getAttributeValue("status")
.equals("failed")) {
passed++;
}
}
if (passed > 0) {
c.setBackground(Color.RED);
}
if (passed == 0) {
c.setBackground(Color.GREEN);
}
}
}
return c;
}
};
testcase_table.setFocusable(false);
testcase_table.setRowSelectionAllowed(false);
testcase_table.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 1) {
JTable target = (JTable)e.getSource();
int row = target.getSelectedRow();
//set_values(doc,25);
set_teststeps(doc, row);
}
}
});
private void DisplayData(List<String> Testcases) {
aModel = new DefaultTableModel() {
// setting the jtable read only
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
// setting the column name
Object[] tableColumnNames = new Object[1];
tableColumnNames[0] = "TestCases";
aModel.setColumnIdentifiers(tableColumnNames);
if (Testcases == null) {
testcase_table.setModel(aModel);
return;
}
Object[] objects = new Object[1];
ListIterator<String> lstrg = Testcases.listIterator();
// populating the tablemodel
while (lstrg.hasNext()) {
String newcus = lstrg.next();
objects[0] = newcus;
aModel.addRow(objects);
}
// binding the jtable to the model
testcase_table.setModel(aModel);
}
有任何想法吗?谢谢你。