Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ActionListener on JLabel or JTable cell

Tags:

I have a JTable with JLabel[][] as data. Now I want to detect a double click on either the JLabel or a table cell (but only in one of the columns). How can I add an Action/MouseListener on JLabel respectively table cell?

like image 620
stefita Avatar asked Sep 04 '09 09:09

stefita


People also ask

What is the difference between ActionListener and MouseListener?

While you can use the MouseListener only in combination with gui elements, the ActionListener is also used when there is no gui, for example in combination with a timer.

Can I add buttons in JTable?

We can add or insert a JButton to JTable cell by customizing the code either in DefaultTableModel or AbstractTableModel and we can also customize the code by implementing TableCellRenderer interface and need to override getTableCellRendererComponent() method.

Is cell editable JTable?

By default, we can edit the text and modify it inside a JTable cell.

How do I add MouseListener to JLabel?

You can try : JLabel nameLabel = new JLabel("Name:"); nameLabel. addMouseMotionListener(new MouseMotionAdapter() { //override the method public void mouseDragged(MouseEvent arg0) { // to do ......................... } }); thats the way I understand your question.


2 Answers

How about:

table.addMouseListener(new MouseAdapter() {   public void mouseClicked(MouseEvent e) {     if (e.getClickCount() == 2) {       JTable target = (JTable)e.getSource();       int row = target.getSelectedRow();       int column = target.getSelectedColumn();       // do some action if appropriate column     }   } }); 
like image 97
Vinay Sajip Avatar answered Sep 18 '22 09:09

Vinay Sajip


Basically the same suggestion as the one already accepted except:

a) you should handle mousePressed, not mouseClicked. A mouseClicked event is only fired when a mousePressed and mouseReleased event is generated at the same pixel location. You if the user moves the mouse even 1 pixel while double clicking you will not get the expected double click.

b) Also you may want to consider using the columnAtPoint() and rowAtPoint() methods to get the clicked cell. Although it probably doesn't make a difference in this case, it will matter if you ever try to use a MouseListener for right mouse clicks, since the selection isn't changed. So if you get in the habit of using this method you won't have problems in the future.

like image 37
camickr Avatar answered Sep 18 '22 09:09

camickr