class GameFrameClass extends javax.swing.JFrame {
public void MyFunc()
{
UserButton.setText(Str);
UserButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
UserButtonActionPerformed(evt);
}
});
getContentPane().add(UserButton);
}
private void UserButtonActionPerformed(java.awt.event.ActionEvent evt) {
//print some stuff after mouse click
}
}
In someother class i define this function
void functionAdd()
{
GameFrameClass gfc = new GameFrameClass()
gfc.MyFunc()
System.out.println("PRINT THIS AFTER MOUSE CLICK")
}
If someone can look into this code. I want to wait on the mouse click . Is there a way i can print the line System.out.println("PRINT THIS AFTER MOUSE CLICK") after the mouse is being clicked . For now this happens immediately and i am not able to wait for the mouse click . Is there a way of doing it ? Apart from doing it inside the function UserButtonActionPerformed() . Please let me know .
This is a really "bad" way to do it...
private void UserButtonActionPerformed(java.awt.event.ActionEvent evt) {
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
System.out.println("PRINT THIS AFTER MOUSE CLICK");
removeMouseListener(this);
}
});
}
A better way would be to have a flag in the actionPerformed method that would "enable" a mouse listener (which you added earlier). This listener would check the flag on each click and when set to true it would flip the flag (to false) and process the event...
It's hard to tell from the wording, but I assume he or she simply wants to execute code after the button is triggered (and not actually wait). For that, you need to add the code inside the method being invoked inside the actionlistener (in this case UserButtonActionPerformed).
So:
private void UserButtonActionPerformed(java.awt.event.ActionEvent evt) {
System.out.println(...);
}
Also, following the Java coding conventions will help people answering your questions in the future.
You can always wait in UserButtonActionPerformed by defining it in the same class. If that is the case then you should not have the problem you are facing
Events are managed on a different thread which is the event dispatching thread, they are not managed by the thread that is executing your code (which presumably is the main thread).
This means that you can attach listeners to GUI elements but the only thing you can do to "wait" for the click is to execute the code inside the actionPerformed callback.
There is no way to pause the execution since the addActionListener doesn't do anything to effectively catch the event, it just adds the listener. Theoretically you could lock the main thread waiting to be notified by the event dispatch one but that would just be bad design.
Related
Let's say i have a listener attached to a button. When i press this button, actionPerformed is called and i set a label as visible. Then the calculate() method runs(which has some really long calculations inside it and it takes time). Then i wanna print the results with the show() method.
Thing is that i know for a fact that the label will be set as visible after all the code inside actionPerformed will be executed.
So my question is : How should i set the calculate method to run on background? Threads? SwingTimer? SwingWorker? I haven't found an ideal way yet.
class ButtonListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent e) {
calculateLbl.setVisible(true);
calculate();
show();
}
}
Your problem is one of Swing concurrency: When calculate() is called on the Swing event thread, the long-running code hampers the event thread, preventing it from painting to the JLabel. The solution is to run calculate in a background thread, and then be notified when it is done. When notification occurs, call show(). A SwingWorker would work great for this since it comes with its own notification mechanism.
e.g.,
#Override
public void actionPerformed(ActionEvent e) {
calculateLbl.setVisible(true);
new SwingWorker<Void, Void>() {
public Void doInBackground() throws Exception{
calculate(); // this is run in a background thread
// take care that calculate makes no Swing calls
return null;
}
protected void done() {
show(); // this is run on the Swing event thread
}
}.execute();
}
Caveat: code not tested/compiled/nor run.
A problem with the above code is that it does not handle any exceptions that might be thrown within the calculate method, and a cleaner better way to do this is to create a SwingWorker variable, attach a PropertyChangeListener to it, and when its SwingWorker.StateValue is SwingWorker.StateValue.DONE, call get() on the SwingWorker and handle any possible exceptions there.
So I am currently doing some work with Multi-Threading in Java and I'm pretty stuck on a, most likely, simple thing.
I currently have a JButton that, when pressed invokes the method as follows:
private void clickTest() throws InterruptedException{
statOrganizer.incrementHappiness();
Thread t = new Thread(new Happiness(workspaceHappy));
t.start();
}
and then takes around 10-30 seconds to complete. During this time however, it is still possible to re-click the JButton so that it messes with how the information is displayed.
What I want to do is during the time this particular thread is "alive", disable the button so that it is no longer possible to click it(and thus activate this thread once it's already going). Once the thread is finished, I want to re-enable the button again.
The button code just looks like this
button.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
if (evt.getClickCount() == 1) {
try {
clickTest();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Disable the button right before starting the thread. In the thread, at the end, post an event that would re-enable the button (using invokeLater).
You may also need a cancel option, but that's a separate question.
Try the following:
button.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent evt) {
if (evt.getClickCount() == 1) {
try {
clickTest();
button.setEnabled(false);//this assume 'button' is final
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
Then, modify the run method of your Happiness class:
public void run()
{
//your processing code here
...
button.setEnabled(true);
//reference to button can be passed in constructor of Happiness
// or access using getter, ... This really depend on your implementation.
}
The nice solution for this is to use a glass pane to capture all events and stopping them from propagating to any of your UI elements on the panel under the glass pane. Of course while you only have one or two, you can call setEnabled(false) on them manually but glass panes give you more flexibility, you'll never have to worry about adding a new element to your UI and forgetting to disable it during background processing.
Probably an overkill for one button though.
Another, unrelated thing you should consider is the use of Executors instead of launching threads for background tasks. It results in cleaner and more scalable code.
I hava a GUI that has a button that need to be pressed periodically in the sense it should pause in between. But i am not able to do that. I have tried with Thread.sleep(). Below is the code.
protected Object doInBackground() throws Exception {
while(true){
btnSend.doClick();
try {
Thread.sleep(2000);
continue;
} catch (InterruptedException e1) {
}
}
return null;
}
Can anyone tell me where i am going wrong and how to solve it?
You shouldn't use a SwingWorker for this since you should not call doClick() off the event thread. If al you want to do is make this call intermittently, then simply use a Swing Timer for calls that need to be done intermittently and on the event thread.
int timerDelay = 2000;
new Timer(timerDelay, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
btnSend.doClick();
}
}).start();
Edit
You ask in comment:
But i need to update another UI on that button click event. If i dont use swingworker the other UI will freeze. I have to use swingworker. Is it possible to do so?
You've got it wrong, I fear. The button click and GUI code should all be on the EDT. Any background non-GUI code that is generated by the button click's ActionListener should be done in a SwingWorker but not the click itself.
e.g.,
elsewhere
btnSend.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
new SwingWorker<Void, Void>() {
public Void doInBackground() throws Exception {
//.....
return null;
}
}
}
});
If you need more specific advice regarding your situation, then you'll want to consider creating and posting a Minimal, Complete, and Verifiable Example Program where you condense your code into the smallest bit that still compiles and runs, has no outside dependencies (such as need to link to a database or images), has no extra code that's not relevant to your problem, but still demonstrates your problem.
I have two buttons on my Netbeans GUI form. One button is starting button, and the other is stopping button. When I press the start button, my code runs good, but when I try to stop then the stop button seems disabled. I cannot press the stop button.
My code starts from the GUI, in which this is my code for starting button
private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {
live p=new live(); //this calls the method of my application
p.livecapture();
}
code for stop button
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
mm=2;
}
The following while loop is present in my livecapture() method
while(NewJFrame.mm!=2) {
}
Suggestions:
Make sure your capture loop is off of the event thread.
If on the event thread either move it off or use a Swing Timer.
Give the capture class a state variable that will stop its loop and a setter method that other classes the ability to tell it to stop.
In it's loop, have it check its state variable and if set, stop the loop.
Please read up on and follow Swing naming conventions. Your code does not adhere to them making it hard for outsiders (us!) to read and understand it.
For more help, tell us more about your live class, what it does, what it does when "capturing".
I'm not sure on your situation, but it sounds like you're executing your code from the Event Dispatch Thread (EDT). This is the thread in your program that is responsible for listening to your GUI-generated events (among other things). If your EDT is busy processing the code in the listener for the start button, then it will be blind to any other button presses that happen.
To prevent this, you should make your program multi-threaded. This is a huge topic in any programming language, but here is a simple example of one of the many ways it could be done in Java, using a Swing Worker:
class MyWorker extends SwingWorker<Void, Void> {
public Void doInBackground() {
// The code you want to run
return Void;
}
}
MyWorker thread = new MyWorker();
startButton.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
thread.execute();
}
} );
endButton.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent e ) {
thread.cancel();
}
} );
Related to my previous question: Call repaint from another class in Java?
I'm new to Java and I've had a look at some tutorials on SwingWorker. Yet, I'm unsure how to implement it with the example code I gave in the previous question.
Can anyone please explain how to use SwingWorker with regards to my code snippet and/or point me towards a decent tutorial? I have looked but I'm not sure I understand yet.
Generally, SwingWorker is used to perform long-running tasks in Swing.
Running long-running tasks on the Event Dispatch Thread (EDT) can cause the GUI to lock up, so one of the things which were done is to use SwingUtilities.invokeLater and invokeAndWait which keeps the GUI responsive by which prioritizing the other AWT events before running the desired task (in the form of a Runnable).
However, the problem with SwingUtilities is that it didn't allow returning data from the the executed Runnable to the original method. This is what SwingWorker was designed to address.
The Java Tutorial has a section on SwingWorker.
Here's an example where a SwingWorker is used to execute a time-consuming task on a separate thread, and displays a message box a second later with the answer.
First off, a class extending SwingWorker will be made:
class AnswerWorker extends SwingWorker<Integer, Integer>
{
protected Integer doInBackground() throws Exception
{
// Do a time-consuming task.
Thread.sleep(1000);
return 42;
}
protected void done()
{
try
{
JOptionPane.showMessageDialog(f, get());
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
The return type of the doInBackground and get methods are specified as the first type of the SwingWorker, and the second type is the type used to return for the publish and process methods, which are not used in this example.
Then, in order to invoke the SwingWorker, the execute method is called. In this example, we'll hook an ActionListener to a JButton to execute the AnswerWorker:
JButton b = new JButton("Answer!");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
new AnswerWorker().execute();
}
});
The above button can be added to a JFrame, and clicked on to get a message box a second later. The following can be used to initialize the GUI for a Swing application:
private void makeGUI()
{
final JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().setLayout(new FlowLayout());
// include: "class AnswerWorker" code here.
// include: "JButton" b code here.
f.getContentPane().add(b);
f.getContentPane().add(new JButton("Nothing"));
f.pack();
f.setVisible(true);
}
Once the application is run, there will be two buttons. One labeled "Answer!" and another "Nothing". When one clicks on the "Answer!" button, nothing will happen at first, but clicking on the "Nothing" button will work and demonstrate that the GUI is responsive.
And, one second later, the result of the AnswerWorker will appear in the message box.
Agree:
Running long-running tasks on the Event Dispatch Thread (EDT) can cause the GUI to lock up.
Do not agree:
so one of the things which were done is to use SwingUtilities.invokeLater and invokeAndWait which keeps the GUI responsive..
invokeLater still runs the code on the EDT, and can freeze your UI!! Try this:
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
At least I, cannot move my mouse once I click the button which triggers the actionPerformed with the above code. Am I missing something?