2013-12-09 73 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); 

      } 
     }); 

它会解决问题。刚删除了所有的单元格编辑器代码。有一个初始列选择存在,但它工作正常。

相关问题