2015-08-19 105 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; 
     } 
    } 

}