[英]JAVA - How to change JTable row color after clicking on it?
我是Java初学者。 我用一个填充了数据库的JTable创建了一个应用程序。 在我的数据库中,我有一些“新闻”。 在我的JTable中,我显示“新闻”的标题,当用户单击一行时,它会显示一个弹出窗口,其中包含新闻的正确内容。 但是我想给用户点击时“已读”的单元格上色。
我使用自己的TableModel。
我希望我清楚...
如果我需要输入一些代码,请告诉我什么...
找到了有关如何在mouseClick上获取表单元格的示例: http ://codeprogress.com/java/showSamples.php?index=52&key= JTableValueofSelectedCell
您可以使用它来获取选定的行和列。
然后,您需要创建一个自定义TableCellRenderer(可能作为内部类),以便它可以使用选定的行和列数据并将单元格的背景设置为突出显示的颜色
public class JTableTest extends JFrame {
private JTable table;
private int col;
private int rowz;
/**
* Create the frame.
*/
public JTableTest() {
initComponents();
}
private void initComponents() {
/** any other components */
table = new JTable();//create the table
table.setDefaultRenderer(Object.class, new CustomModel());
table.addMouseListener(new CustomListener());
}
public class CustomListener extends MouseAdapter {
@Override
public void mouseClicked(MouseEvent arg0) {
super.mouseClicked(arg0);
//get the clicked cell's row and column
rowz = table.getSelectedRow();
col = table.getSelectedColumn();
// Repaints JTable
table.repaint();
}
}
public class CustomModel extends DefaultTableCellRenderer {
private static final long serialVersionUID = 1L;
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
JLabel label = (JLabel) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
Color c = Color.WHITE;//define the color you want
if (isSelected && row == rowz & column == col)
c = Color.GREEN;
label.setBackground(c);
return label;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.