Cell Handler Interaction in JTable

Is there a way to get the cell handler to respond to mouse events such as mice?

+3
source share
2 answers

Never tried, but I think you need:

a) create your own renderer for drawing a cell in two states

b) you need to keep track of which cell should be drawn in the "mouse over" state

c) add a mouse listener to track mouse input / output and mouseMoved. With each event, you will need to update a variable that keeps track of which cell is located above the mouse. You can use columnAtPoint () and rowAtPoint () JTable methods

d), , repaint() . getCellRect(), ,

e), , reset "mouse over", .

+3

, camickr, . MouseMotionListener JTable , , , . - , . , , , . -. , , , , , JToggleButton ( ). :

package guipkg;

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;

public class Grid extends JTable implements MouseListener {

int currentCellColumn = -1;
int currentCellRow = -1;
int previousCellColumn = -1;
int previousCellRow = -1;

public void detectCellAtCursor (MouseEvent e) {
    Point hit = e.getPoint();
    int hitColumn = columnAtPoint(hit);
    int hitRow = rowAtPoint(hit);
    if (currentCellRow != hitRow || currentCellColumn != hitColumn) {
        this.editCellAt(hitRow, hitColumn);
        currentCellRow = hitRow;
        currentCellColumn = hitColumn;
    }

}


}







package guipkg;

import javax.swing.table.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;


public class TCEditor extends AbstractCellEditor implements TableCellEditor  {

    /**
     * A toggle button which will serve as a cell editing component
     */

    JToggleButton togglebutton = new JToggleButton();





    public Component getTableCellEditorComponent (JTable Table, Object value, boolean isSelected, int rindex, int cindex) {

        /**
         * We're adding an action listener here to stop editing as soon as the state of JToggleButton is switched.
         * This way data model is updated immediately. Otherwise updating will only occur after we've started to
         * edit another cell.
         */

        togglebutton.addActionListener(new ActionListener() {
            public void actionPerformed (ActionEvent e) {
                stopCellEditing();
            }
        });


        if (value.toString().equals("true")) {
            togglebutton.setSelected(true);
        }
 else {
            togglebutton.setSelected(false);
 }
        togglebutton.setBorderPainted(false);
        return togglebutton;
    }

    public Object getCellEditorValue () {
        return togglebutton.isSelected();
    }


}

, -

0

Source: https://habr.com/ru/post/1766031/


All Articles