Disable JButton after click and enable when it done it's job - java

I have a JButton which has an ActionListener, which does its job as many times as I click it. Below is my code:
mouseListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton source = (JButton) e.getSource();
source.setEnabled(false);
try {
RequestCommon.ctbCookie = jtf.getText();
System.out.println(RequestCommon.ctbCookie);
HttpURLConnection connection = HttpURLConnectionBuilder.getConnection(RequestCommon.login, RequestCommon.getCtb888Headers());
String connectionOuput = HttpURLConnectionBuilder.getConnectionOuput(connection);
System.out.println(connectionOuput);
new Player(new BufferedInputStream(new FileInputStream(new File("sounds/8.mp3")))).play();
} catch (IOException e1) {
e1.printStackTrace();
} catch (JavaLayerException e1) {
e1.printStackTrace();
}
source.setEnabled(true);
}
}
jb1.addActionListener(mouseListener);
I want it so that no matter how many times I click while the job is running it won't execute again. When the job is done, if I click again, the job will run again. I don't know how to do that, please tell me if you know, thanks!

Long running code should NOT execute on the Event Dispatch Thread (EDT). You need to start a separate Thread to do you HTTP request.
The easiest way to do this is to use a SwingWorker. You can disable the button before you start the worker and then the worker has a done() method that is invoked and you can enable the button.
Read the section from the Swing tutorial on Concurrency in Swing for more information about the EDT and a working example of a Swing worker.
Edit:
People seem confused about event handling. The listeners for an event are invoked before the next event is handled. So in the case of "double clicking" on the button. The button is disable on the first click and the long running task is started. The second click is then received on the disable button so the ActionListener is not invoked.
Here is some old code I have lying around which was written before a SwingWorker existed. The basic logic for the "Start in New Thread" button is:
disable the button so it can't be click while processing is happening
simulate a long running task by looping 10 times and sleeping
enable the button so the task can be done again
Here is the code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
* A couple of notes about long running tasks and GUI updates:
*
* 1) all GUI painting should be done in the event thread
* 2) GUI painting is not done until the event thread processing is done
*
* This means that long running code (database access, file processing ...)
* should not be done in the event thread. A new thread can be created for
* these tasks.
*
* Most Swing methods are not thread safe. If the long running task needs
* to update the GUI for any reason then the SwingUtilities class
* should be used to add code to the event thread.
*
* See the Swing tutorial on "Using Threads" for more information
* http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html
*/
public class InvokeLaterTest extends JFrame
implements ActionListener, Runnable
{
JLabel status;
JButton eventThread;
JButton newThread;
JButton stop;
Thread thread;
int i;
boolean stopProcessing;
public InvokeLaterTest()
{
status = new JLabel( "Ready to Process:" );
status.setHorizontalAlignment( JLabel.CENTER );
getContentPane().add(status, BorderLayout.NORTH);
eventThread = new JButton( "Start in Event Thread" );
eventThread.addActionListener( this );
getContentPane().add(eventThread, BorderLayout.WEST);
newThread = new JButton( "Start in New Thread" );
newThread.addActionListener( this );
getContentPane().add(newThread, BorderLayout.EAST);
stop = new JButton( "Stop Processing" );
stop.addActionListener( this );
getContentPane().add(stop, BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent e)
{
// Code is executing in Event thread so label will not be updated
// and the Stop button will not be enabled.
if (e.getSource() == eventThread)
{
stopProcessing = false;
run();
}
// Code is executing in a new thread so label will be updated
else if (e.getSource() == newThread)
{
stopProcessing = false;
thread = new Thread( this );
thread.start();
}
else
{
stopProcessing = true;
status.setText("Processing Stopped");
setButtons( true );
}
}
public void run()
{
setButtons( false );
for (i = 1; i < 10; i++)
{
if ( stopProcessing ) return;
System.out.println("ProcessingFile: " + i);
// SwingUtilities makes sure code is executed in the event thread.
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
status.setText("Processing File: " + i);
status.paintImmediately(status.getBounds());
}
});
// simulate log running task
try { Thread.sleep(1000); }
catch (Exception e) {}
}
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
status.setText("Finished Processing");
setButtons( true );
}
});
}
private void setButtons(boolean value)
{
eventThread.setEnabled( value );
newThread.setEnabled( value );
}
public static void main(String[] args)
{
JFrame frame = new InvokeLaterTest();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setLocationRelativeTo( null );
frame.show();
}
}
A SwingWorker is similar to the above logic but:
you need to disable the button outside the SwingWorker
the worker will create the Thread for you and execute the code
when the worker is finished the done() method of the worker is invoked so you can enable the button.

You should use if and check if the button is enabled before executing your code.
JButton source = (JButton) e.getSource();
if(source.isEnabled()) {
.
.
.
execute your code

JButton source = (JButton) e.getSource();
if (source.isEnabled()) {
Executors.newSingleThreadScheduledExecutor().execute(() -> {
source.setEnabled(false);
--your code here--
source.setEnabled(true);
}
);
}
};

Added a completedTime variable to hold the timestamp as when the action is complete, and every event has the time when it is generated, compare and return if it is less than the completed time
long completedTime;
mouseListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
JButton source = (JButton) e.getSource();
long timeStamp = e.getWhen();
if (timeStamp < completedTime) {
System.out.println("returned");
return;
}
// source.setEnabled(false);
try {
RequestCommon.ctbCookie = jtf.getText();
System.out.println( RequestCommon.ctbCookie );
HttpURLConnection connection = HttpURLConnectionBuilder.getConnection(RequestCommon.login, RequestCommon.getCtb888Headers());
String connectionOuput = HttpURLConnectionBuilder.getConnectionOuput(connection);
System.out.println(connectionOuput);
new Player(new BufferedInputStream(new FileInputStream(new File("sounds/8.mp3")))).play();
} catch (IOException e1) {
e1.printStackTrace();
} catch (JavaLayerException e1) {
e1.printStackTrace();
}
// source.setEnabled(true);
completedTime = System.currentTimeMillis();
}
};

Related

Is it okay to use thread.sleep() when coding a bot?

I'm trying to code a primitive spammer. Is it okay to use thread.sleep() when coding a bot?
I'm a novice programmer. If there is any place in my code to fix it, I would appreciate it if you let me know. I may have used JComponents improperly. If it catches your eye, you can specify. Thank you.
Note: "It looks like your post is mostly code; please add some more details." I'm writing this note because I can't find any more details to add. Sorry
public class Spammer extends JFrame implements Runnable{
private boolean running = false;
private JButton jButton1;
private JLabel jLabel1, jLabel2;
private JScrollPane jScrollPane1;
private JSpinner jSpinner1;
private JTextArea jTextArea1;
public Spammer() {
setLayout(null);
jLabel1 = new JLabel("Text: ");
jTextArea1 = new JTextArea(10,28);
jLabel2 = new JLabel("Interval: ");
jSpinner1 = new JSpinner();
jScrollPane1 = new JScrollPane();
jButton1 = new JButton("Spam");
jButton1.setSize(350, 60);
jButton1.setLocation(100, 220);
jLabel1.setSize(50, 150);
jLabel1.setLocation(15, 10);
jLabel1.setFont(new Font("Verdana" , Font.BOLD , 14));
jTextArea1.setSize(350, 150);
jTextArea1.setLocation(100, 10);
jLabel2.setSize(80, 25);
jLabel2.setLocation(15, 180);
jLabel2.setFont(new Font("Verdana" , Font.BOLD , 12));
jSpinner1.setSize(350, 25);
jSpinner1.setLocation(100, 180);
getContentPane().add(jLabel1);
getContentPane().add(jTextArea1);
getContentPane().add(jLabel2);
getContentPane().add(jSpinner1);
getContentPane().add(jScrollPane1);
getContentPane().add(jButton1);
setTitle("Spammer by Me");
setLocationRelativeTo(null);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(500, 340));
pack();
jButton1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jButton1ActionPerformed();
}
} );
}
private void jButton1ActionPerformed() {
if(!running) {
jTextArea1.setEnabled(false);
jSpinner1.setEnabled(false);
jButton1.setText("Spamming in 3 seconds...");
jButton1.setEnabled(false);
running = true;
new Thread(this).start();
}else {
jTextArea1.setEnabled(true);
jSpinner1.setEnabled(true);
jButton1.setText("Spam");
running = false;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Spammer().setVisible(true);
}
});
}
public void run() {
Robot robot = null;
try {
robot = new Robot();
} catch (AWTException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
int[] keys = new int[jTextArea1.getText().length()];
if((int) jSpinner1.getValue() < 0) {
jSpinner1.setValue((int) 0);
}
int interval = (int) jSpinner1.getValue();
for(int i = 0 ; i < keys.length; i++) {
keys[i] = KeyEvent.getExtendedKeyCodeForChar(jTextArea1.getText().charAt(i));
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jButton1.setEnabled(true);
jButton1.setText("Stop");
while(running) {
for(int i = 0 ; i < keys.length; i++) {
robot.keyPress(keys[i]);
robot.keyRelease(keys[i]);
}
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
The key principle at work here is primarily the 'EDT' - the Event Dispatch Thread. This is a thread that does GUI stuff - if for example you drag the titlebar of a completely different app's window across the screen, and this moves that app's window over yours, the EDT is hard at work redrawing everything. The EDT is the thread that sees you press your mouse down on a button, and will render the button in the 'pressed in' view.
The EDT is the only thread from which you can do GUI stuff, whether it is to retrieve info, such as getText(), or whether it is to change things, such as updating the text of a label or whatnot.
The EDT is also the thread you're in when your code runs that you registered as a handler for events, such as the code that responds to a button click or whatnot.
You therefore must not sleep on the EDT (Because then your app looks non-responsive; the thread that responds to button clicks or repaints what needs repainting is not actively running), but you can only fetch GUI data / set GUI stuff from the EDT.
The rules:
Do not interact with any GUI elements unless you are in the EDT
Never sleep in the EDT
Your code is broken, not because you sleep (that's fine - that run() method is not in the EDT), but because you do GUI stuff from this non-EDT thread.
You need to do a careful dance here: You want to sleep (not allowed on the EDT), but interact with GUI elements, such as the interval box, to know how long to sleep, which can only be done on the EDT.
To do this, you can 'send' code to run in the EDT via SwingWorkers, or simply via:
SwingUtilities.invokeAndWait(() -> {
// code that will run in the EDT goes here
});
You can't set any variables from within this code, but you can use AtomicReference and friends to create objects you can change. So, instead of:
int[] keys = new int[jTextArea1.getText().length()];
if (jSpinner1.getValue() < 0) {
jSpinner1.setValue(0);
}
int interval = (int) jSpinner1.getValue();
which is doing GUI stuff, do:
AtomicInteger interval = new AtomicInteger();
SwingUtilities.invokeAndWait(() -> {
int[] keys = new int[jTextArea1.getText().length()];
if (jSpinner1.getValue() < 0) {
jSpinner1.setValue(0);
}
interval.set((int) jSpinner1.getValue());
};

How to run two JOptionPane's with threads

I have to set two Dialogs and i want to Stop the first one and then start the second. Can anyone please help me to fix it
JOptionPane msg = new JOptionPane("your score is: " + getScore(), JOptionPane.INFORMATION_MESSAGE);
final JDialog dlg = msg.createDialog("Game Over");
dlg.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
dlg.dispose();
}
}).start();
dlg.setVisible(true);
the second Dialog would be the same like
JOptionPane message = new JOptionPane("Highscore: " + getHighscore(), JOptionPane.INFORMATION_MESSAGE);
final JDialog dialog = message.createDialog("Game Over");
dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
now i want to start this Dialog after the first will be closed.
Recommendations:
For the sake of Swing thread safety, use a Swing Timer rather than directly using a background thread.
Make it a non-repeating timer.
Inside the timer's ActionListener, close/dispose of the current dialog and open the 2nd.
e.g., (code not tested)
final JDialog myModalDialog = ....;
final JDialog mySecondDialog = ....;
int timerDelay = 3000;
Timer timer = new Timer(timerDelay, e -> {
myModalDialog.dispose();
mySecondDialog.setVisible(true);
});
timer.setRepeats(false);
timer.start();
myModalDialog.setVisible(true);
Alternatively: use a single dialog and swap views using a CardLayout tutorial

Best way to make a thread start from a jbutton?

I have 15 different threads running all with dynamic input from the user. I need these Threads to run ONLY when my JButton is pressed. I know i didnt supply the code for the button but its just a simple deceleration.
JButton JButton_Button1 = new JButton("Start");
To clarify one more time i just want the thread to start only when JButton_Button1 is clicked
new Thread() {
int counter = 10;
public void run() {
while(counter >= 0) {
JLabel_MistyvaleLoot.setText("Test" + (counter--));
try{
Thread.sleep(1000);
} catch(Exception e) {}
}
}
}.start();
If you're looking to have 15 threads running, but you want them to do nothing except when a JButton is pressed, then consider using a fixed-size thread pool. Try using:
private ExecutorService threadPool = Executors.newFixedThreadPool(15);
This constructs 15 processing threads that will idle until you submit a task. If you are looking to submit a task when the JButton is pressed, then you should add an ActionListener. That is, try this:
JButton jButton1 = new JButton("Start");
jButton1.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent event){
threadPool.submit(new Runnable(){
int counter = 10;
public void run() {
while(counter >= 0) {
JLabel_MistyvaleLoot.setText("Test" + (counter--));
try {
Thread.sleep(1000);
} catch(InterruptedException e) {
}
}
}
});
}
});
To get one of the fifteen threads to run the task, you call threadPool.submit() and to get the button to respond to a click, you call jButton1.addActionListener().

strange bug - how to pause a java program?

I'm trying to:
display a text in a jLabel,
wait for two seconds,
then write a new text in the jLabel
this should be simple, but I get a strange bug:
the first text is never written, the application just waits for 2 seconds and then displays the final text. here is the example code:
private void testButtonActionPerformed(java.awt.event.ActionEvent evt) {
displayLabel.setText("Clicked!");
// first method with System timer
/*
long t0= System.currentTimeMillis();
long t1= System.currentTimeMillis();
do{
t1 = System.currentTimeMillis();
}
while ((t1 - t0) < (2000));
*/
// second method with thread.sleep()
try {
Thread.currentThread().sleep(2000);
} catch (InterruptedException e) {}
displayLabel.setText("STOP");
}
with this code, the text "Clicked!" is never displayed. I just get a 2 seconds - pause and then the "STOP" text.
I tried to use System timer with a loop, or Thread.sleep(), but both methods give the same result.
Just to provide more background on Andrew Thompson's comment: the EDT is responsible for handling gui updates. If you block it using Thread.sleep(...) those updates are blocked as well. That's why you don't see the first text - the EDT just can't do the update on the label.
Here's a runnable example which does what you're after. As Andrew Thompson's comment stated, a SwingWorker is a good way to approach this problem.
The basic principal is to never block the Event Dispatch Thread. That's the thread responsible for repainting the GUI and responding to user interaction, so if you do something computationally expensive on the EDT, your GUI will stop responding.
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.concurrent.ExecutionException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingWorker;
public class ButtonTest {
public static void main(String[] args) {
// create a frame and a button
JFrame frame = new JFrame();
final JButton button = new JButton("Button");
frame.add(button);
// add an action listener to the button
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// change the button text right away
button.setText( "Clicked" );
// create a SwingWorker which simply waits 2000 milliseconds
// simulating a computation being performed
SwingWorker<String, Object> worker = new SwingWorker<String, Object>() {
#Override
public String doInBackground() {
// it's safe to call Thread.sleep( ) here
// doInBackground is executed on a separate worker
// thread
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
return "Done";
}
#Override
protected void done() {
// done() is executed back on the Swing thread
// so it's safe to updated the state of the button
try {
button.setText(get());
} catch (Exception e) { }
}
};
// run the worker
worker.execute();
}
});
frame.setSize( 300, 300 );
frame.setVisible( true );
}
}
You are messing with the event dispatcher thread.
That will cause un-expected UI behavior as you are seeing. If you plan to do these type of animations, make sure to read up on what #Andrew Thompson suggested and also, see if you can read this - Filthy rich clients
Better to use a Swing Timer as shown in curde-example below:(yes, it is crude, I did not worry about stopping the timer etc):
public class DelayTest extends JPanel{
JLabel messageLabel = new JLabel();
JButton actionButton = new JButton("Click Me");
String[] messages = {"Clicked", "Stop!"};
int i=0;
public DelayTest(){
super();
add(messageLabel);
add(actionButton);
actionButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
Timer timer = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if(i<=1)
messageLabel.setText(messages[i++]);
}
});
timer.start();
}
});
}
}
Edit
Why not stop the Timer:
#Override
public void actionPerformed(ActionEvent evt) {
if (i <= 1) {
messageLabel.setText(messages[i++]);
} else {
((Timer)evt.getSource()).stop();
}
}
});

Swing invokeLater never shows up, invokeAndWait throws error. What can I do?

I have this code:
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
try {
dialog.handleDownload();
} catch (IOException io) {
io.printStackTrace();
}
}
});
} catch(Exception io) { io.printStackTrace(); }
in the handleDownload I'm reading an inputstream, calculating a progress bar's value, and setting it to that. So, when I click a button, a new JFrame opens up and does all the stuff I wrote above.
If I have the dialog.handleDownload by itself ( in no SwingUtilities method ), it freezes until the operation is finished. If I add it in a invokeLater it's closed very fast ( I can't see anything, and the operation is not finished ). If I add it in a invokeAndWait I get the invokeAndWait cannot be called from the event dispatcher thread error. What should I do?
It looks like you could make use of SwingWorker. This allows you to defer an expensive operation to a background thread (keeping your GUI responsive) and when the operation is finished, do some stuff to the GUI.
Edit: Example
Here's a bit more complex example that shows how to use the basics of SwingWorker but also how to publish/process intermediate results.
public static void main(String[] args) {
final int SIZE = 1024*1024; //1 MiB
//simulates downloading a 1 MiB file
final InputStream in = new InputStream() {
int read = 0;
public int read() throws IOException {
if ( read == SIZE ) {
return -1;
} else {
if ( read % 200 == 0 ) {
try { Thread.sleep(1); } catch ( InterruptedException e ) {}
}
read++;
return 5;
}
}
};
final JProgressBar progress = new JProgressBar(0, SIZE);
final JButton button = new JButton("Start");
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
button.setText("Working...");
SwingWorker<byte[], Integer> worker = new SwingWorker<byte[], Integer>() {
#Override
protected byte[] doInBackground() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
for ( int read = -1; (read = in.read(buff)) != -1; ) {
baos.write(buff, 0, read);
publish(read);
}
return baos.toByteArray();
}
#Override
protected void process(List<Integer> chunks) {
int total = 0;
for ( Integer amtRead : chunks ) {
total += amtRead;
}
progress.setValue(progress.getValue() + total);
}
#Override
protected void done() {
try {
byte[] data = get();
button.setText("Read " + data.length + " bytes");
} catch (Exception e) {
e.printStackTrace();
}
}
};
worker.execute();
}
});
JFrame frame = new JFrame();
frame.setLayout(new BorderLayout());
frame.add(button, BorderLayout.NORTH);
frame.add(progress, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack(); frame.setVisible(true);
}
Edit: Changed the example to drive a progress bar as if a download were taking place.
If you are doing that in response to a button click, you are already in the event thread so invokeAndWait is actually going in the wrong direction.
You need to start a new thread to execute the handleDownload thread that is NOT a the event dispatch thread--BUT
When running in your new thread, be sure that any GUI updates use invokeAndWait or preferably invokeLater to get back to the EDT.
The simple rules to remember:
Any thread handed to you by Swing is the EDT, so do all the GUI stuff on it you want
Do ALL updates of GUI elements on the EDT (ONLY).
Do anything that takes a long time on a non-EDT thread (Start a new thread).
Use invokeLater to get back to the EDT from a non-EDT thread
You shouldn't be accessing your inputStream in the event thread. Spawn a new thread which actually does the bulk of the handleDownload() work, then make the last operation performed by that thread be to call SwingUtilities.invokeLater() with the code that actually shows and populates the dialog.
What does "handleDownload" do? Time consuming things should not be done in the event dispatcher thread. If something is consuming lots of CPU cycles in the event dispatcher thread, then the display will freeze until it's done. You are far better off in a case like that invoking a normal thread (not using SwingUtilities) to do the processing outside of the event dispatcher thread, and in that thread using SwingUtilities.invokeLater to send back notifications that things have changed (like updating a progress bar) at regular intervals.
What it sounds like you need is a SwingWorker. This will allow you to have the file download take place in a separate thread that doesn't bother the EDT.
Your code would look something like this:
class Downloader extends SwingWorker<String, Void> {
#Override
public String doInBackground() {
dialog.handleDownload();
return "done";
}
#Override
protected void done() {
try {
someLabel.setText(get());
} catch (Exception ignore) {
}
}
}

Categories