-1

I need help to add an event when clicking with the mouse on the columns identifiers, I'm using DefaultTableModel

public class TableData extends JTable{

    private final DefaultTableModel model;
    private final ObjectIterable objI;

    public TableData(ObjectIterable s){
        objI = s
        model = new DefaultTableModel();
        initTable();
        loadTable();
        addTableEvent();
    }

    private void initTable(){
        model.setColumnIdentifiers(new String []{"Name","Type"});
        setModel(model);
        setEnabled(false);
    }

    private void loadTable(){
        for(ObjI s : objI){
            String type = s.getType();
            String value = s.value();
            insertRow(value, type);
        }
    }

    public void insertRow(String param, String type){
        model.insertRow(0, new String[]{param,type});
    }

    private void addTableEvent(){
        JTable table = this;
        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
//                super.mouseClicked(e);
                if(e.getClickCount() == 2){
                    if(table.rowAtPoint(e.getPoint()) < 0){
                        System.out.println("clicket");
                    }
                }
            }
        });
    }
}

I need to know in which column the click was made. Thanks for your help.

abdiel
  • 1
  • 1
  • You should extend the table model, not the JTable. – Hovercraft Full Of Eels Jul 11 '21 at 00:28
  • This question is asking about *... clicking with the mouse on the columns identifiers* - The column identifiers are part of the table header, not the table. This question was closed as a duplicate of (https://stackoverflow.com/questions/4795586/determine-which-jtable-cell-is-clicked) where the answer shows how to add a listener to the table, not the header. I re-opened the question. – camickr Jul 11 '21 at 03:09
  • *java DefaultTableModel header click event* - a `TableModel` has nothing to do with a mouse click. A TableModel is only used to hold the data. The view is responsible for handling the events. – camickr Jul 11 '21 at 03:17

1 Answers1

0

I need help to add an event when clicking with the mouse on the columns identifiers,

You need to add the listener to the table header, not the table.

I need to know in which column the click was made.

Something like:

table.getTableHeader().addMouseListener(new MouseAdapter() 
{
    @Override
    public void mouseClicked(MouseEvent e) 
    {
        JTableHeader header = (JTableHeader)e.getSource();
        int column = header.columnAtPoint( e.getPoint() );
        System.out.println( column );
    }
});
camickr
  • 321,443
  • 19
  • 166
  • 288