JTable change cell background at mouse click - after release change background back?

前端 未结 3 1675
孤城傲影
孤城傲影 2021-01-06 21:30

my question is, how to solve following problem:

If i click on a cell in a JTable, i want to change its background. If i release the mousebutton, i want the backgroun

3条回答
  •  梦毁少年i
    2021-01-06 22:12

    For doing it in the visual realm you need

    • a MouseListener which sets some state in cell-coordinates on pressed and resets that state on released
    • a PropertyChangeListener listeneng to that state which repaints the cell on change
    • a custom renderer which sets a custom background for the cell that is flagged

    some code for the listeners

        MouseListener l = new MouseAdapter() {
    
            /** 
             * @inherited 

    */ @Override public void mousePressed(MouseEvent e) { JTable table = (JTable) e.getComponent(); int col = table.columnAtPoint(e.getPoint()); int row = table.rowAtPoint(e.getPoint()); if (col < 0 || row < 0) { table.putClientProperty("pressedCell", null); } else { table.putClientProperty("pressedCell", new Point(col, row)); } } /** * @inherited

    */ @Override public void mouseReleased(MouseEvent e) { ((JTable) e.getComponent()).putClientProperty("pressedCell", null); } }; table.addMouseListener(l); PropertyChangeListener property = new PropertyChangeListener() { @Override public void propertyChange(PropertyChangeEvent evt) { JTable table = (JTable) evt.getSource(); Point cell = evt.getNewValue() != null ? (Point) evt.getNewValue() : (Point) evt.getOldValue(); if (cell != null) table.repaint(table.getCellRect(cell.y, cell.x, false)); } }; table.addPropertyChangeListener("pressedCell", property);

    Highlighting the cell in SwingX (cant resist :-)

        HighlightPredicate predicate = new HighlightPredicate() {
    
            @Override
            public boolean isHighlighted(Component renderer, ComponentAdapter adapter) {
                Point p = (Point) adapter.getComponent().getClientProperty("pressedCell");
                return p != null && p.x == adapter.column && p.y == adapter.row;
    
            }
        };
        table.addHighlighter(new ColorHighlighter(predicate, Color.YELLOW, null, Color.YELLOW, null));
    

    For core Swing, either implement a custom TableCellRenderer or subclass the JTable and override prepareRenderer to set the background color according to the cell flag, as explained in Rob's Table Row Rendering

提交回复
热议问题