2013-12-09 75 views
2

我發現代碼在單擊JTable標題時選擇特定列。對於我的模塊,如果有人選擇了一個JTable單元格,所有先前的列選擇都必須被擦除。我可以在單元格編輯器中成功更改table.setColumnSelectionAllowed(true);table.setRowSelectionAllowed(false);如何在表格單元格編輯器中給出JTable單元格選擇背景和前景色

現在

  1. 我無法還原默認選擇前景色和背景色。
  2. 選擇單元格後,如果選擇表格標題,則無法清除上一個表格單元格選擇。

HeaderLocation.java

public class HeaderLocation { 
    private JTable getTable() { 
     int rows = 32, cols = 4; 
     String[] colIds = { "column 1", "column 2", "column 3", "column 4" }; 
     Object[][] data = new Object[rows][cols]; 
     for(int row = 0; row < rows; row++) { 
      for(int col = 0; col < cols; col++) { 
       data[row][col] = "item " + (row*cols+col+1); 
      } 
     } 
     DefaultTableModel model = new DefaultTableModel(data, colIds); 
     final JTable table = new JTable(model); 
     final JTableHeader header = table.getTableHeader(); 
     Enumeration<TableColumn> columns = table.getColumnModel().getColumns(); 
     while(columns.hasMoreElements()){ 
      columns.nextElement().setCellEditor(new CustomCellEditor()); 
     } 
     //table.setCellEditor(new CustomCellEditor()); 
     header.setReorderingAllowed(false); 
     header.addMouseListener(new MouseAdapter() { 
      public void mouseClicked(MouseEvent e) { 
       int col = header.columnAtPoint(e.getPoint()); 
       System.out.printf("click cursor = %d%n", 
            header.getCursor().getType()); 
       if(header.getCursor().getType() == Cursor.E_RESIZE_CURSOR) 
        e.consume(); 
       else { 
        //System.out.printf("sorting column %d%n", col); 
        table.setColumnSelectionAllowed(true); 
        table.setRowSelectionAllowed(false); 
        table.clearSelection(); 
        table.setColumnSelectionInterval(col,col); 
        //tableModel[selectedTab].sortArrayList(col); 
       } 
      } 
     }); 

     return table; 
    } 

    private JMenuBar getMenuBar() { 
     final JMenu view = new JMenu("view"); 
     ActionListener l = new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       JMenuItem item = (JMenuItem)e.getSource(); 
       String className = item.getActionCommand(); 
       changePLAF(className, view.getTopLevelAncestor()); 
      } 
     }; 
     UIManager.LookAndFeelInfo[] info = UIManager.getInstalledLookAndFeels(); 
     for(int j = 0; j < info.length; j++) { 
      JMenuItem item = new JMenuItem(info[j].getName()); 
      item.setActionCommand(info[j].getClassName()); 
      item.addActionListener(l); 
      view.add(item); 
     } 
     JMenuBar menuBar = new JMenuBar(); 
     menuBar.add(view); 
     return menuBar; 
    } 

    private void changePLAF(String className, Component c) { 
     try { 
      UIManager.setLookAndFeel(className); 
     } catch(ClassNotFoundException cnfe) { 
      System.err.println("class not found: " + cnfe.getMessage()); 
     } catch(InstantiationException ie) { 
      System.err.println("instantiation: " + ie.getMessage()); 
     } catch(IllegalAccessException iae) { 
      System.err.println("illegal access: " + iae.getMessage()); 
     } catch(UnsupportedLookAndFeelException ulafe) { 
      System.err.println("unsupported laf: " + ulafe.getMessage()); 
     } 
     SwingUtilities.updateComponentTreeUI(c); 
    } 

    public static void main(String[] args) { 
     HeaderLocation test = new HeaderLocation(); 
     JFrame f = new JFrame(); 
     f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     f.setJMenuBar(test.getMenuBar()); 
     f.getContentPane().add(new JScrollPane(test.getTable())); 
     f.pack(); 
     f.setLocation(200,200); 
     f.setVisible(true); 
    } 
} 

CustomCellEditor.java

public class CustomCellEditor extends AbstractCellEditor implements TableCellEditor{ 

    private JComponent component = new JLabel(); 

    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { 
     System.out.println(row + "," + column); 
     //if(getClickCountToStart() == 2) 
     //{ 
     try{  
      table.clearSelection(); 
      table.setColumnSelectionAllowed(false); 
      table.setRowSelectionAllowed(false); 
     } 
     catch(Exception e) 
     { 
      System.out.println("Exception::->" + e.getMessage()); 
     } 
     //} 
     // Configure the component with the specified value 
     component.setOpaque(isSelected); 
     ((JLabel)component).setText((String)value); 
     component.setForeground(table.getSelectionForeground()); 
     component.setBackground(table.getSelectionBackground()); 
     component.setEnabled(false); 
     // Return the configured component 
     return component; 
     } 

    @Override 
    public Object getCellEditorValue() { 
     // TODO Auto-generated method stub 
     return ((JLabel)component).getText(); 
    } 
} 

我真的很感激與此相關的任何幫助。

+1

那不是編輯!請閱讀相應的教程章節(請參閱swing標籤wiki中的參考資料),以便理解渲染器/編輯器 – kleopatra

+0

不相關的概念:即使它是一個功能齊備的編輯器(又名:用於改變單元格內容)會嚴重不當,因爲它不能改變呼叫者的狀態。 – kleopatra

+0

現在,如果它是這樣的,當用戶單擊特定的單元格時,如何將列選擇恢復爲單元格選擇。 – user1709952

回答

1
new JTable(model) 
     { 
      public Component prepareRenderer(TableCellRenderer renderer, int row, int column) 
      { 
       Component c = super.prepareRenderer(renderer, row, column); 

       // Color row based on a cell value 

       if (isRowSelected(row)){ //When A row is selected 
            c.setBackground(getBackground());//Set Background 
            c.setForeground(color.RED); 
       } 

       return c; 
      } 
// Use if(!isRowSelected(row)){} if want to change non-selected row color or background 
} 
+0

嗯,感謝渲染器。在這段代碼中,我需要一個單元格和列選擇而不是行選擇。 – user1709952

0

謝謝kleopatra。我只是添加了表格鼠標監聽器的代碼,如下所示: -

table.addMouseListener(new MouseAdapter() { 
      public void mouseClicked(MouseEvent e) { 

        //System.out.printf("sorting column %d%n", col); 
        table.setColumnSelectionAllowed(false); 
        table.setRowSelectionAllowed(false); 
        table.setCellSelectionEnabled(true); 
        //tableModel[selectedTab].sortArrayList(col); 

      } 
     }); 

它會解決問題。剛刪除了所有的單元格編輯器代碼。有一個初始列選擇存在,但它工作正常。

相關問題