Essentially what I'm trying to do is have an int edited when an action event is performed in Java. I've been trying to figure this out for days D:. I've tried to use arrays to do it, but wasn't successful also.
The problem is that the edit int isn't necessarily edited for the whole main method because it's being edit in a separate method. What I'm trying to do is basically be able to tell if the action performed was actually performed.
If you could tell me a different way to be able to tell if an action has been performed that's better than editing an int than by all means please tell me.
oButton9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
xButton9.setVisible(false);
oButton9.setVisible(false);
nine.repaint();
nine.add(olabel);
int x =1;
}
} );
if (x == 1) {
blah blah blah
}
You need to consider the scope of the variable. Your "x" must be an instance variable, then you will be able to use it as you want.
What you are doing now, is changing the value of the local variable i, you have to declare instance variable in your class and change its value, because only then you will be able to use it in other methods.
You have to note that after running oButton9.addActionListener(...), the if statement will run immediately, so even if you can somehow set the x from the actionPerformed, it would not be useful, because the program flow won't stop at addActionListener until the actionPerformed is called.
If you're trying to do something when the button is clicked, why just not put it in the actionPerformed function?
By the way, you can define the x variable as a field in your class, and then:
class Test {
...
public int x = 0;
public void doSomething() {
...
oButton9.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Test.this.x = 1;
}
});
...
}
public static void main(String[] args) {
new Test().doSomething();
}
}
Related
I am someone new to Java and working with the robot class. I would like to make an emergency stop function for my robot so when it does something wrong I can make the automation end. While robot so far has been easy the key listener escapes me, please explain in a "my first keylistener" style, thank you!
Here is what I have so far:
public static void keyboard(String input, HWND window) throws Exception {
System.out.println("Keyboard Typing:\n" + input);
//This is just to stop the error, but I don't know how
//to actually listen
KeyEvent e = null;
for (int i = 0; i < input.length(); i++) {;
keepFocus(window);
if(stopBot(e /*How to pass a key press*/) == true){
break;
}
char c = input.charAt(i);
keyboardHandler(c);
Thread.sleep(80);
}
}
public static boolean stopBot(KeyEvent e){
if(e.getKeyCode() == KeyEvent.VK_END){
return true;
}
return false;
}
There is other code but this is all that is relevant to my problem
The easiest way I could think about implementing a key event is by making your current class extend a Key Listener class. Basically, you want your current class to be listening for keystrokes in the background. You'll start by adding the implementation to your class name:
public YourClassName implements KeyListener {
}
Now, your class is able to listen for key strokes in the background. You'll now need to add a listener in your code and then give it instructions on what to do when hit. You'll add the listener by invoking the following method:
this.addKeyListener()
You can also replace "this" with any other instantiated object capable of handling action events. Now, you just need to be able to instruct the program on what to do when the listener picks up a key stroke event. The key listener will evoke one method from the KeyListener class you are extending: keyPressed(KeyEvent e), keyRelease(KeyEvent e), or keyTyped(KeyEvent e). These are the functions that will then run whatever code you'd like when a key-event is picked up and passed through the function. You will need to override these methods like so:
#Override
public void keyReleased(KeyEvent e) {
//whatever you want to happen in the case of
this event, I assume stop your robot
}
So, as you can see, you don't need to worry about invoking your own KeyEvent, Java's addKeyListener will take care of this as long you've extended the class and given instructions on what to do for each event! Hope this helps!
how to access value from outside the actionlistener
jbtnOne.addActionListener(new ActionListener() {
private String ana_data;
#SuppressWarnings("override")
public void actionPerformed(ActionEvent le) {
ana_data=jtf.getText();
}
});
pos_pred=def_pred(f_path,ana_data,prob_p,poslen,pcount);
neg_pred=def_pred(f_path1,ana_data,prob_n,neglen,ncount);
I need to take the data from outside the ActionListener inside the method given after that? can someone please help me?
There is no way of doing that.
The reason is that the ActionListener is executed later in time when the rest of the method is already run.
So if you want to work with something that depends on the action listener you have to move it there (or in a method tat is called from the ActionListener .
One of possible general patterns to tackle problems where some part of your code depends on values from code executed asynchronously is to use promises (CompletableFuture in Java). Generally it is advisable to design your overall code asynchronously in such situations, so that the method producing the value and the method requiring the value can both proceed at some even at some later point in time. From you question it is not clear if you can design it that way in your case. So I will assume you cannot. If your caller cannot behave asynchronously and needs the result of an asynchronous operation within a synchronous flow, then you will need to block the thread waiting for the result:
CompletableFuture<String> anaDataPromise = new CompletableFuture<>();
jbtnOne.addActionListener(new ActionListener() {
#SuppressWarnings("override")
public void actionPerformed(ActionEvent le) {
anaDataPromise.complete(jtf.getText());
}
});
anaData = anaDataPromise.get(); // will block until action performed
// anaData = anaDataPromise.get(10, TimeUnit.MINUTE); // will block until action performed or for max of 10 minutes
If you could permit the code that needs the anaData value to be fully asynchronous, then you could write it in a non-blocking fashion:
CompletableFuture<String> anaDataPromise = new CompletableFuture<>();
jbtnOne.addActionListener(new ActionListener() {
#SuppressWarnings("override")
public void actionPerformed(ActionEvent le) {
anaDataPromise.complete(jtf.getText());
}
});
anaDataPromise.whenComplete((anaData, throwable) -> {
if (throwable != null) {
throw new RuntimeException(throwable);
}
// do something with anaData value
});
// this point is reached immediately as the above code simply declares
// the action that will run later, the actions themselves are not yet run
The "username" will not be printed when the button (action) is triggered the first time. When the button is pressed the second time, the value is printed out once. On third click the value is printed out twice.. Can someone point out my mistake?
*This is my first question, do give hints on posting better questions :D
Here's the main method:
public class DMS implements ActionListener{
private static String username;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
LoginFrame login = new LoginFrame();
login.setVisible(true);
}
public DMS(JTextField textField1) {
DMS.username = textField1.getText();
}
#Override
public void actionPerformed(ActionEvent e) {
System.out.println(username);
}
}
And here's the action listener, which is in a jframe:
private void cmd_loginActionPerformed(java.awt.event.ActionEvent evt) {
ActionListener actionListener = new DMS(JTextField1);
someButton.addActionListener(actionListener);
}
When the control is transferred to your action listener, you are trying to print the username that you got during the initialization - which is empty.
What you need to do is:
Keep a reference of the JTextField in your DMS class
On actionPerformed(), get the data from the component.
This will ensure that you are always fetching the latest information.
Hope that helps.
Try removing this statement from cmd_loginActionPerformed so that its not being invoked every time an ActionEvent occurs
someButton.addActionListener(actionListener);
Since you have not shown the complete code, it cannot be seen when cmd_loginActionPerformed is called, but from the described behavior, it seems you are adding an action listener every time an action happens. You need to attach an action listener only once (this will fix your incremental printing), and that has to be done before any user action occurs, i.e. do it in initialization (this will fix the non-print issue on first action).
username will assigned once at the time of DMS object creation.
public DMS(JTextField textField1) {
DMS.username = textField1.getText();
}
To get the last value from the form we need to call getText(); from the actionPerformed(ActionEvent e) method
public void actionPerformed(ActionEvent e) {
DMS.username = textField1.getText();
System.out.println(username);
}
I have a class with two JSpinner objects in them, x and y.
I have one change Listener which is added to both.
can someone tell me how I can implement my change listener so that the listener can tell the difference between the two objects.
e.g. Pseudocode:
if(source equals x)
do this
else if(source equals y)
do that
Thanks guys,
You can simply use an anonymous class to implement the listener for each spinner
For example if you want to implement change listener to x, you can do something like:
x.addChangeListener(new ChangeListener()
{
public void stateChanged(ChangeEvent e)
{
}
});
and same thing for y
It's more prudent (as Ali has pointed out, +1) to use a single listener per control where possible. It isolates the event/action and makes it generally easier to read and make sense of...
If you can't see yourself using this, then every EventObject has a getSource method which is a reference to the control which raised the event...
public void stateChanged(ChangeEvent e)
{
if (e.getSource() == xControl) {
// xControl updated
} else if (e.getSource() == yControl) {
// yControl updated
}
}
I'm playing around with Java and I've got myself a class for an NPC in a game. One method is called when they collide with another object:
public void collided_in_to(Entity ent) {
if(ent.equals(game.player)) {
this.speak = "Ouch!";
}
}
What I want to do, which I figured was going to be simple, is set this.speak to "" after a given amount of seconds. Coming from a web background, I was looking for an equivalent of Javascripts setTimeout().
I've tried using various timer snippets, such as using Swing timers, but in that case it seemed like every timer would call the same public void actionPerformed(ActionEvent e) method, and so with multiple timers for different events I had no way to differentiate between them. Others used inline anonymous classes, but then I have no way to pass non-final parameters to it.
Is there something I'm missing for this use case, where I want very small simple things to happen after a set time? (Instance method called, variable set, etc.)
Thanks!
How about writing you own simple Timer? I would think of something like this :
public class Timer {
long start = 0;
long delay;
public Timer(long delay) {
this.delay = delay;
}
public void start() {
this.start = System.currentTimeMillis();
}
public boolean isExpired() {
return (System.currentTimeMillis() - this.start) > this.delay;
}
}
Then instantiate the Timer class as a class member and call start() when you want to start the timer.
In your method you call
public void collided_in_to(Entity ent) {
if(ent.equals(game.player)) {
if(this.timer.isExpired()) this.speak = "";
else this.speak = "Ouch!";
}
}
If you're using a game loop you could simply make a seconds passed verification.
Have you considered threads? Thread.sleep() can be used fairly effectively to time it.