MouseListener not catching the mousePressed/Clicked - java

Ok so I'm not sure why my MouseListener isn't working but I think it might be because I implemented both the ActionListener and MouseListener into the class. Would this cause the class to have an issue?
actionPerformed method:
public void actionPerformed(ActionEvent e){...
...
}
mouseClicked method:
public void mouseClicked(MouseEvent arg0) {
...
}
Is it because it's only listening to the actionPerformed method and never entering the MouseListener? If what I suspect is correct, how would I allow it to work together?
EDIT: I've narrowed it down to something is wrong in the MouseListener. It doesn't ever get any input from the mouse at all, do I have to specify the area it should be listening to?
public void mousePressed(MouseEvent arg0) {
System.out.println("Inside timer is running");
if(timer.isRunning() == true){
System.out.println("Inside timer is running");
Point p = arg0.getPoint();
}
}

You ask:
Ok so I'm not sure why my MouseListener isn't working but I think it might be because I implemented both the ActionListener and MouseListener into the class. Would this cause the class to have an issue?
No, this should not affect things at all. Your problem most likely lies elsewhere in code not shown.
Having said this, I'd like to add that almost none of my GUI classes implement either of these or other listener interfaces, since I feel that this would be asking the class to have too much responsibility, making it harder to debug now or upgrade later. Instead I favor either anonymous inner classes that then call control methods, or a completely separate control/listener class(es).
Edit
I don't think that your posted code and text is adequate to allow us to understand your problem enough to answer it other than to say that the problem lies elsewhere. If you don't get a decent answer soon, consider creating and posting a Minimal, Complete, and Verifiable Example Program.
Edit 2
You state in comment:
I don't think I could post anymore code that may clear it up since this is a huge program. This class alone has 300 lines but I know everything else works just the MouseListener isn't working like it should
Up to you what you should do next, but if this were my code, and I were running into these problems, I would work some more on trying to isolate the problem, including refactoring my code so that that I eventually come up with the smallest critical code that reproduces the problem. You're probably coming here at too premature of a stage in your debugging, forcing you to post "what if" scenarios, and for us to shrug our shoulders and say, "who knows".
Edit 3
You ask:
do I have to specify the area it should be listening to?
You have to specify what component to listen to. MouseListeners listen to components. But again, this is little more than more "what if's" and "who knows"...

Related

How to force repaint in Swing while debugging? [duplicate]

I cannot seem to force a layout in Swing. I have a JComponent added to a JLayeredPane and I set a border on the JComponent. Then, I want to immediately re-draw everything - not in the sense of "please do this asap" like invalidate(), but synchronously and immediately. Any help? I cannot seem to find the right method of doing this, and all my reading about invalidate(), validate(), repaint(), doLayout(), etc is just confusing me more!
According to this (see the section titled "Synchronous Painting") the paintImmediately() method should work.
The most reliable way to get Swing to update a display is to use SwingUtilities.invokeLater. In your case, it would look something like
SwingUtilities.invokeLater(new Runnable {
public void run() {
somecomponent.repaint();
}
});
I realize the 'invokelater' does not exactly sound like it does anything immediate, but in practice, events posted in this way tend execute pretty quickly compared to just calling e.g. somecomponent.repaint() directly. If you absolutely must make your control code wait for the GUI to update, then there is also invokeAndWait, but my experience is that this is rarely necessary.
See also: document on event dispatch in Swing.
This is super old, but I found a simple solution, which I'll show with a JPasswordField:
var pw = new JPasswordField();
...
pw.paint(pw.getGraphics()); // paints immediately

How can I fix the actionPerformed method freezing when the mouse is moved within the pane?

In a Swing application when the mouse is moved within the frame, the actionPerformed method stops cycling. How can I fix this?
Here's the basic layout of my program:
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
// main game loop
}
}
public void paintComponent(Graphics g) {
// render loop
}
I found a similar question here. The user found that by lowering the polling rate of the mouse they fixed the problem; however I cannot change the polling rate on my apple trackpad, and no other solutions were offered. Also it is an inelegant solution that would require the user to change settings, and honestly there has to be a better way to fix the problem.
Basically the question boils down to this:
Is there a way for me to change the polling rate from within my program? I did some research and couldn't find a solution.
How can I disable mouse movement events, so as to not slow down my game loop? (Also perhaps move it to a separate process, and use the mouses x and y position provided by that process for logic in the game loop.)
What alternate solution can I implement to fix this problem?
I think you need to implement the "ActionListener" where you can take it, because when you are moving will work the ActionListener, when you will click, it will be already ActionEvent.
Also you can get more from:
https://docs.oracle.com/javase/tutorial/uiswing/events/mouselistener.html
and
How can I get the location of the mouse pointer in a JPanel (Without any operation of the Mouse)?

How can you keep a JPanel from closing on System.exit(0)

I have a program that I am terminating with the System.exit(0); command.
When this happens the JPanel closes. I would like it to rename open so I can view the state at termination. Is there a way of keeping the Jpanel open or is there a better command than System.exit()?
not sure why a down vote I asked a simple question and someone answered it. I can't do it that way so try something else. Going to use a true false to test where to enter the simulation loop.
regarding:
Is there a way of keeping the Jpanel open or is there a better command than System.exit()?
The best solution: Don't call System.exit(...). Why? Because System.exit(0) closes the JVM, and so all Java processes running on that JVM will shut down when System.exit(0) is called.
As for "better command", that all depends on your need. If you just want to close a window such as a JDialog, then call myWindow.setVisible(false);. If you want to close it and release resources, then myWindow.dispose();.
Note: I suspect that you might have multiple windows open, perhaps multiple JFrames. If so, I strongly urge you to read: The Use of Multiple JFrames, Good/Bad Practice?
You also posted in comments:
I would like to keep the Jpanel open, but stop the simulation from running. I need to stop the Sim when certain conditions are met. so I wrote a stop()
So your question is in fact an XY Problem where you ask how to solve a specific code problem (keep a JPanel open after calling System.exit(0)) when the best solution is to use a completely different approach. Better that you tell us the overall problem that you're trying to solve rather than how you're currently trying to solve it, because System.exit isn't going to be part of the best solution.
Likely the best solution is to well separate your simulation model from its view (the GUI), to be able to give the model functionality that allows it to stop without closing down the JVM -- impossible for me to say how given our current level of knowledge about your problem -- and then reflect the stopping of the model in the view, again without shutting down the system.
The key to all of this will lie in the details of your current program, including the logic that underpins your simulation, and if you need more specific and likely more helpful answers, you're again going to want to improve your question, providing us with much more specific information about your code, your problem and with posting of pertinent code, preferably as a minimal example program.
Have you tried an approach similar to:
Do something when the close button is clicked on a JFrame
Basically, you're grabbing the Window closing event by setting a listener on the frame
You can then .dispose() the appropriate jpanel/frame if you want
JFrame is window and JPanel is a container. The moment the JPanel instance loses its reference, it will be garbage collected
How can JPanel be disposed after the panel has been removed from the JFrame
Disposing JFrame by clicking from an inner JPanel
import javax.swing.JOptionPane;
/*Some piece of code*/
frame.addWindowListener(new java.awt.event.WindowAdapter() {
#Override
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
//delete this code if you want and replace with .dispose() or anything
if (JOptionPane.showConfirmDialog(frame,
"Are you sure to close this window?", "Really Closing?",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE) == JOptionPane.YES_OPTION){
//choose to close JVM here if you want
System.exit(0);
}
}
});
Here's a way, by overriding the SecurityManager for the JVM:
//set your security manager
static{
SecurityManager s = new DontCloseOnExitSecurityManager();
System.setSecurityManager(s);
}
static class DontCloseOnExitSecurityManager extends SecurityManager{
public void checkExit(int code){
//here you can put a check to see if you really do want to close - like if the JFrame is still open.
if(/*do some check*/ 13 == code)
super.checkExit(code);
throw new SecurityException("13 is unlucky, you shouldn't system exit on it.");
}
}
}
You'll need to find an appropriate place to put it in, and also how to do your checks (in checkExit).
Apologies for inaccuracies, I'm not in front of an IDE to test this right now.

actionCommand in Swing Action seems to be dependent of I18N

Here on Stack Overflow I read a lot about using Swing Actions rather than ActionListeners, so I started to use them within the application's menu.
Everything worked out nice until I introduces I18N, only to find out that the actionCommand of the MenuItem changes accordingly to the language.
Here is what I do:
class ExitAction extends AbstractAction {
public void init() {
putValue(Action.NAME, messageSource.getMessage("app.gui.action.exitApplication"));
}
}
My guess is, that I did understand something wrong and this is not the way to do what I want to do.
Can you please help me?
Two things...
Firstly, NAME affects the text of button, but if not specified, will also set the actionCommand. Property. Instead I think you're after the ACTION_COMMAND_KEY property
Secondly, there should actually be little need for it, as the Action is self contained, hat is, it is it's own ActionListener, so when actionPerformed is called on your Action, you are guaranteed the association

GUI creation code layout theory?

This question is not so much a "How to create a gui", but more of a "where to create the gui".
I have some java code that checks to make sure the drivers needed are in place:
public boolean confirmDrivers() {
/* some logic */
return someDriver.exists();
}
it gets called as:
if (confirmDrivers()) {
createGUI();
}
Is it a bad idea to have the actionlisteners defined for some buttons in createGUI() ? it seems out of place because that function is mostly just assignment (ie - myButton.setToolTipText("hay guyz click here!"); ), and the listeners contains minor logic (mostly to call other functions that DO contain the logic.
Just curious as to what others do in this situation.
Split the GUI out from the business logic altogether. Wrap up the GUI as it's own class and attach the actionlisteners in the constructor, and maybe pass in whatever handles the actual business logic. Something like this:
if (confirmDrivers()) {
new GUI(someBusinessLogicController);
}

Categories