【问题标题】:How to give JTable cell selection background and foreground color in table cell editor如何在表格单元格编辑器中赋予 JTable 单元格选择背景和前景色
【发布时间】:2013-12-09 13:29:01
【问题描述】:

我找到了在单击 JTable 标题时选择特定列的代码。对于我的模块,如果有人选择了 JTable 单元格,则必须删除所有先前的列选择。我成功地在单元格编辑器中更改了table.setColumnSelectionAllowed(true); 或table.setRowSelectionAllowed(false);。

现在

  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();
    }
}

我非常感谢与此相关的任何帮助。

【问题讨论】:

  • 那不是编辑器!请阅读相应的教程章节(参见 swing 标签 wiki 中的参考)以了解渲染器/编辑器的概念
  • 不相关:即使它是一个成熟的编辑器(又名:其角色是更改单元格内容),它也将是严重的行为不端,因为它必须不改变调用者的状态。
  • 现在如果是这样,当用户单击特定单元格时,如何将列选择恢复为单元格选择。
  • 使用鼠标监听器(别忘了阅读教程:)
  • 感谢 kleopatra。我刚刚为桌面鼠标侦听器添加了代码,如下所示:-

标签: java swing jtable


【解决方案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
}

【讨论】:

  • 感谢渲染器。在这段代码中,我需要一个单元格和列选择而不是行选择。
【解决方案2】:

感谢克娄巴特拉。我刚刚为桌面鼠标侦听器添加了代码,如下所示:-

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);  

            }  
        });  

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

【讨论】:

    猜你喜欢
    • 2015-11-29
    • 2011-09-24
    • 2015-10-09
    • 2020-01-20
    • 2020-12-25
    • 2015-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多