2015-08-19 106 views
0

我是Java初学者。 我创建了一个带有填充数据库的JTable的应用程序。 在我的数据库中有一些'新闻'。在我的JTable中,我显示“新闻”的标题,当用户点击一行时,它会显示一个弹出窗口,其中包含新闻的正确内容。 但我想给用户点击时读取的单元着色。JAVA - 点击它后如何改变JTable的行颜色?

我用我自己的TableModel。

我希望我清楚......

如果我需要把一些代码,告诉我什么,请...

+0

欢迎SO!张贴必要的最低限度的代码,以确定您正在尝试解决的困惑(即,让某人可以准确查看您需要帮助的位置)。 – J0e3gan

+0

实现表格单元格渲染器并更改用于渲染的组件的颜色。 –

回答

0
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; 
     } 
    } 

}