Re: Right-click in a JList and associated action
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Hendrik Maryns schreef:
| Hi all,
|
| I have a little Swing app which has as its main area a JList containing
| formulas. It is possible to edit a formula through an edit menu and I
| want to provide this menu if the use right-clicks on a formula.
|
| After creating the edit menu and adding it to the menubar, I ask for its
| popup menu with editMenu.getPopupMenu() and added the following to the
| JList (result is the JList being constructed):
|
| // mouse listener listens for double click to invoke the edit action and
| // for popup action to show the edit menu
| // as a popup
| result.addMouseListener(new MouseAdapter() {
|
| ~ @Override
| ~ public void mousePressed(final MouseEvent e) {
| ~ this.maybeShowPopup(e);
| ~ }
|
| ~ @Override
| ~ public void mouseReleased(final MouseEvent e) {
| ~ this.maybeShowPopup(e);
| ~ }
|
| ~ @Override
| ~ public void mouseClicked(final MouseEvent e) {
| ~ if (e.getButton() == MouseEvent.BUTTON1 && e.getClickCount() == 2) {
| ~ editAction.actionPerformed(new ActionEvent(this,
| ActionEvent.ACTION_FIRST, "double click"));
| ~ }
| ~ }
|
| ~ private void maybeShowPopup(final MouseEvent e) {
| ~ if (e.isPopupTrigger()) {
| ~ editPopup.show(result, e.getX(), e.getY());
| ~ }
| ~ }
| });
|
| It is a bit strange to have maybeShowPopup twice, but that is necessary
| as documented in
|
<http://java.sun.com/javase/6/docs/api/java/awt/event/MouseEvent.html#isPopupTrigger()>.
|
|
| The problem is, that the actions in the edit menu rely on the active
| formula being selected. When doing a right click, the formula below the
| right click is not selected, so the actions do the wrong things. How
| can I tell the JList to also select the formula with a right-click,
| *before* showing the popup menu?
I found it out now:
@Override
public void mousePressed(final MouseEvent e) {
~ if (e.getButton() == MouseEvent.BUTTON3) {
~ final int index = result.locationToIndex(e.getPoint());
~ result.setSelectedIndex(index);
~ }
~ this.maybeShowPopup(e);
}
I noticed that JList changes selection when pressing the left mouse
button, so that2"s where I put this. It took my quite a headache to find
out why the right mouse button is button 3 though. No indication at all
in http://java.sun.com/javase/6/docs/api/java/awt/event/MouseEvent.html
what the numbers mean!
H.
- --
Hendrik Maryns
http://tcl.sfs.uni-tuebingen.de/~hendrik/
==================
http://aouw.org
Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.4-svn0 (GNU/Linux)
Comment: Using GnuPG with SUSE - http://enigmail.mozdev.org
iD8DBQFIRUVoe+7xMGD3itQRAtDnAJwIHhN6KScj+XKtFuCNUlsaJMqfugCeM53d
SM/UNVllH4CS3U0v8X1z9H0=
=vQHE
-----END PGP SIGNATURE-----