Task: There is a large application in which new jComponent are periodically created. Need to add processing for all of them by mouse clicking on them with the "Alt" key pressed.
It is clear that this needs to be done using component.addMouseListener(). Is there a section of the JComponent creation code where we can insert our code? Or are there other ways to solve the problem?
My code based on Rjelinek's suggestion:
public static void registrationMouseAction() {
Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
@Override
public void eventDispatched(final AWTEvent event) {
if (event instanceof MouseEvent) {
MouseEvent mouseEvent = (MouseEvent) event;
if (mouseEvent.getID() == MOUSE_CLICKED) {
// # left prev
if (mouseEvent.getButton() == 4) {
new BackRecentDefinitionAction().performed();
}
// # right next
if (mouseEvent.getButton() == 5) {
new BackRecentDefinitionAction().performed();
}
// # view modal editor
if (mouseEvent.getButton() == 1 && mouseEvent.isAltDown()) {
new OpenModalEditorRadixObjectsAction().performed();
}
}
}
}
}, AWTEvent.MOUSE_EVENT_MASK);
}
Correction: I need to have the processing of "Alt MouseButton1" for all components in the application (for example, JButton, JPanel, etc.).
CodePudding user response:
the solution for you lies somewhere in this lines. However I must say that on application start up it does make some mouse click on background, that will probably need to be addressed
EDIT
After posting I realized there is a request for alt key down, so I added this condition and it restrict code spam on start up. however its still not optimal
public class Main {
public static void main(String[] args) {
Toolkit.getDefaultToolkit().addAWTEventListener(new AWTListener(), AWTEvent.MOUSE_EVENT_MASK);
//your code
}
private static class AWTListener implements AWTEventListener{
@Override
public void eventDispatched(AWTEvent event) {
if (event instanceof MouseEvent evt && evt.isAltDown()) {
//your mouse event code
}
}
}