I have a JTable
in my Java Swing application and everything works fine in general. I have added a MouseListener
on my JTable
, so whenever I try right clicking on a row in the table, I can capture the event and run a method. However, what I'd like to do is to
- Select the cell
- Get it's value
- Then call the method.
To do this, I must currently left click on the row, then also do a right click on it. Is it possible to select the row/cell right away with only a single click of the right mouse button?
Here is my code so far:
public class MyMouseAdapterTableArticoli extends MouseAdapter {
public void mouseClicked(MouseEvent me) {
JTable t = (JTable)me.getSource();
JMenuItem menuItem;
rowPopUp = t.rowAtPoint(me.getPoint());
if ((me.getClickCount() == 2) && (me.getButton() == MouseEvent.BUTTON1)) {
pulisciTableArtRappre();
if((listaMagazzino != null) && (listaMagazzino.size() > 0)) {
pulisciTableArtMagazzino();
}
popolaCampi(rowPopUp);
} else if (me.getButton() == MouseEvent.BUTTON3) {
JPopupMenu popup = new JPopupMenu();
menuItem = new JMenuItem("Mostra Prezzi di Acquisto");
menuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mostraPrezziAcquisto(rowPopUp);
}//fine metodoVoid
});//fine actionlistener
popup.add(menuItem);
MouseListener popupListener = new PopupListener(popup);
table.addMouseListener(popupListener);
}//fine else e if
}
public void mousePressed(MouseEvent e) {
JTable source = (JTable)e.getSource();
int row = source.rowAtPoint(e.getPoint());
int column = source.columnAtPoint(e.getPoint());
if (!source.isRowSelected(row)) {
source.changeSelection(row, column, false, false);
}
}