JTable clickable header header

I am trying to make a clickable column header (so that the method will be called whenever you click).
Link to the image (since I have no reputation 10 yet) http://img156.imageshack.us/img156/5764/clickablecolumn.png
The column heading is in the red box.
What I have done so far is responsible when any field of a column is clicked (e.g. with James, Benny-G and Rokas). The code:

public void mouseClicked(MouseEvent e)
    {
        System.out.println("Mouse clicked");
        TableColumnModel cModel = table.getColumnModel();//cModel - column model
        int selColumn = cModel.getColumnIndexAtX(e.getX());//gets the selected column by clicked x coordinate
    }
+3
source share
1 answer

You want to add a mouse listener to the table header, which is presented JTableHeader:

JFrame frame = new JFrame();
frame.getContentPane().add(new JScrollPane(new JTable(4, 3) {
  {
    getTableHeader().addMouseListener(new MouseAdapter() {
      @Override
      public void mouseClicked(MouseEvent mouseEvent) {
        int index = convertColumnIndexToModel(columnAtPoint(mouseEvent.getPoint()));
        if (index >= 0) {
          System.out.println("Clicked on column " + index);
        }
      };
    });
  }
}));

frame.pack();
frame.setVisible(true);
+14
source

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


All Articles