Java Break while loop using AWTEventListener - java

I'm trying to break loop using AWTEventListener, but in 'if' after checking if I pressed ctrl+p it says error by the break;
try {
Robot robot = new Robot();
int z = 0;
while(true) {
robot.mouseMove(x + z, y);
z++;
AWTEventListener listener = new AWTEventListener() {
#Override
public void eventDispatched(AWTEvent event) {
try {
KeyEvent evt = (KeyEvent)event;
if(evt.getID() == KeyEvent.KEY_PRESSED && evt.getModifiers() == KeyEvent.CTRL_MASK && evt.getKeyCode() == KeyEvent.VK_P) {
break; //ERROR
}
}
catch(Exception e) {
e.printStackTrace();
}
}
};
Toolkit.getDefaultToolkit().addAWTEventListener(listener, AWTEvent.KEY_EVENT_MASK);
}
} catch (AWTException e) {
}

I don't think you understand what you're doing when creating the listeners. You're basically creating a class right in place, and that class has a method named eventDispatched(). There's no loop inside eventDispatched(), so there's no loop to break out of.
Furthermore, it's probably a mistake to assume the event is a KeyEvent. That's a side note.
Your listener probably needs to set some field that your while loop is looking at. Instead of while(true) you need to do "while(my listener hasn't set some flag to another value)".

Related

How to constantly check if mouse leftclick is being held down in mouseeEvent

static boolean enabled = false;
#Override
public void mousePressed(MouseEvent e) {
enabled = true;
if (e.getButton() == 1) {
try {
do {
while (enabled) {
System.out.println("registered click");
Thread.sleep(1000);
}
} while (e.isMetaDown());
} catch (Exception e1) {
e1.printStackTrace();
}
} else {
JOptionPane.showMessageDialog(frame, "not working");
}
}
#Override
public void mouseReleased(MouseEvent e) {
System.out.println("released");
enabled = !enabled;
}
it will just continue the loop even if i unclick my mouse, if i add a break; in there it will just stop the while loop and not continue checking for the condition. Please how do i constantly check for a condition in the while loop?
Edit:
Ok, I’m using Swing for the framework, and what I’m trying to achieve is that when I click my left mouse button, the loop begins and keeps going while the left mouse button is held down but when I lift my finger and the mouse button is released, the loop stops but it doesn’t stop the loop. It just continues the loop even if I unclick my mouse.
The issue is you can't start an infinite loop here since it will cause a deadlock as soon as the first event occurs. You just need to wait for the function to be called, then update the state accordingly. You can then read and act on the state elsewhere in your program. Since events are in a separate thread than the rest of your program, you can create your loop in the main thread or spawn a new thread.
As a side note, you don't need to check for an exception here. A MouseEvent just stores information about an event. After being created it is created it wont be changed.
static boolean enabled = false;
#Override
public void mousePressed(MouseEvent e) {
// Ignore events if they are not for the button we care about
if (e.getButton() == 1) {
enabled = true;
}
}
#Override
public void mouseReleased(MouseEvent e) {
if (e.getButton() == 1) {
enabled = false;
}
}
// In some other thread (such as the one which created the JPanel)
while (true) {
if (enabled) {
System.out.println("registered click");
Thread.sleep(1000);
}
}

How to stop auto clicker upon pressing a Key

#Override
public void keyPressed(KeyEvent e) {
if ( e.getKeyChar() == 'x' ) {
Clicking = true;
}
try {
if(Clicking == true)
robot = new Robot();
while (true) {
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.delay(1000);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
if(e.getKeyChar() == 'b'){
Clicking = false;
}
} } catch(AWTException awtException) {
awtException.printStackTrace();
}
}
I'm trying to make it so whenever I press b the autoclicker stops it works when I press x but doesn't stop after I press b
You are using the mechanism on the core while, I don't say it is bad, although what about assigning it to methods like run_it and stop_it? Or just, perform_the_click (that cud be more simply).
"I'm trying to make it so whenever I press b the autoclicker stops it works when I press x but doesn't stop after I press b".
I seriously don't see it has sense, try using commas, thus it makes it non-understandable for the community.
Please show more about the project, where does the Clicking just came from?
You require another thread to listen to your 'b's click. Because it is running on the current thread it blocks listening to inputs.
An idea of something like this:
if(e.getKeyChar() == 'x' ) {
if(robot == null) {
robot = new Robot(someObjectIWantToBringOver);
Thread thread = new Thread(robot);
thread.start();
}
}
if(e.getKeyChar() == 'b' ) {
if(robot != null) {
robot.stop();
robot = null;
}
}
//In your Robot class
class Robot implements Runnable {
private volatile boolean running = true;
private final Object xyz;
public Robot(Object abc??) {
this.xyz = abc;
}
...
public void run() {
while(running) {
try{
xyz.mousePress(InputEvent.BUTTON1_DOWN_MASK);
Thread.sleep(1000);
xyz.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
}catch(Exception e) {}
}
}
public void stop() {
running = false;
}
}
Looks like a fun project. Have fun!

How to programmatically simulate arrow key presses in Java FX

I want to make my JFX application simulate arrow key presses (when they are registered in a TextField), but I can't figure out how to send anything other than Strings or bytes.
I'm imagining something like this:
static EventHandler<KeyEvent> KEY() {
E = new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent ke) {
if (ke.getCode().equals(KeyCode.UP)) {
try {
//someObject.SimulateKeyPress(KeyCode.UP);
//OR
//coolObject.SendKey((char)KEY_UPKEY));
} catch (Exception ex) {
//Teleport goats
}
}
}
};
return E;
}
Use the class Robot
try {
Robot r = new Robot();
//there are other methods such as positioning mouse and mouseclicks etc.
r.keyPress(java.awt.event.KeyEvent.VK_UP);
r.keyRelease(java.awt.event.KeyEvent.VK_UP);
} catch (AWTException e) {
//Teleport penguins
}
You cannot instantiate the type Robot.
You should rather do :
Robot robot = com.sun.glass.ui.Application.GetApplication().createRobot();

Default close shortcut does not work

The default close shortcut (Cmd+q on Mac) doesn't work on this program i coded in java, do you know why?
I am an absolute beginner and would be glad if you helped me!
The code:
public static void main(String[] args) throws IOException, AWTException{
final Robot robot = new Robot();
robot.delay(2000);
while(true)
{
{
robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);
robot.delay(50);
}
}
}
}
That would be because Java is trying to be as cross-platform (or platform-independent) as it can be. You could make your own closing shortcut, using the Key class explained in your previous questions (specifically: How to cast a keyboard event). However, I don't think you could detect mac-specific keys, unless you dive into JNI (Java Native Interface), but if you are a beginner I wouldn't recommend it just yet.
For example, say you would like the shortcut to be CTRL+Q. Add another field in your Key class:
private boolean ctrlPressed = false;
Then, make a pressing check:
#Override
public void keyPressed(KeyEvent e)
{
//Previous code
if(e.getKeyCode() == KeyEvent.VK_CONTROL)
{
ctrlPressed = true;
}
}
#Override
public void keyReleased(KeyEvent e)
{
//Previous code
if(e.getKeyCode() == KeyEvent.VK_CONTROL)
{
ctrlPressed = false;
}
}
And finally, the Q part:
#Override
public void keyTyped(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_Q && ctrlPressed)
System.exit(0);
}

CheckBoxMenuItem and ButtonGroup

There are CheckBoxMenuItems и ButtonGroup. When I set the listener for current CheckBoxMenuItem, the condition is checked and the error is produced in this listener. I have active another CheckBoxMenuItem, and it is not necessary for me, even I will write "return".
Problem is that the method cannot throw exceptions and the class is anonymous.
Here is the code:
mUserMode.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if(currentCard == 0) {
return;
}
boolean IsEmptyFields = true, isCheckedAnswers = false;
// check if all fields is fill in ...
endOfCycle: for(Component component: panelForAddingQuesions.getComponents()) {
if(component instanceof JTextField) {
JTextField question = (JTextField)component;
if(question.getText().length() == 0) {
IsEmptyFields = false;
break endOfCycle;
}
}
}
// and if there is one correct answer in every question
// check if all fields is fill in ...
for(Entry<JTextField, ArrayList<JCheckBox>> entrySets: equivalenceOfQuestionFiledsAndItsAnswers.entrySet()) {
isCheckedAnswers = false;
for(JCheckBox checkbox: entrySets.getValue()) {
if(checkbox.isSelected()) {
isCheckedAnswers = true;
}
}
}
if(IsEmptyFields) {
JOptionPane.showMessageDialog(MainActivity.this,
"Error", "Error",
JOptionPane.ERROR_MESSAGE);
}
else if(isCheckedAnswers) {
JOptionPane.showMessageDialog(MainActivity.this,
"Error","Error",
JOptionPane.ERROR_MESSAGE);
}
else {
cardLayout.last(cardPanel);
currentCard = 0;
}
// It doesn't help
//MainActivity.this.mAdminMode.setEnabled(true);
}
});
There is the method(аctionPerformed) in anonymous class. I want on a condition to cancel switching ChechBoxItem of elements i.e. to stop this operation. But as ,anyway , the method аctionPerformed is completed, there will be automatic a switching of checkboxes as it will be notified View. And I need to prevent it directly in a method actionPerformed
You should call MainActivity.this.mAdminMode.setSelected(true);, not setEnabled(true).

Categories

Resources