I have a program where the user can press a key to perform an action. That one event takes a small amount of time. The user can also hold down that key and perform the action many times in a row. The issues is that the keyPress() events are queued up faster than the events can be processed. This means that after the user releases the key, events keep getting processed that were queued up from the user previously holding down the key. I also noticed that the keyRelease event doesn't occur until after the final keyPress event is processed regardless of when the key was actually released. I'd like to be able to either
1. Detect the key release event and ignore future keyPress events until the user actually presses the key again.
2. Not perform a subsequent keyPress event until the first is one finished and then detect when the key is not pressed, and just stop.
Does anyone know how to do this?
Disclaimer: I am not feeling well so this code is horrific, as though.. it too is sick.
What I want to happen: To access DirectInput to obtain a keyboard state, instead of events. That is far beyond the scope of this question though. So we will maintain our own action state.
The problem you are having is that you are executing your action within the UI thread. You need to spawn a worker thread and ignore subsequent events until your action is completed.
In the example I've given I start a new action when the letter 'a' is pressed or held down. It will not spawn another action until the first action has completed. The action updates a label on the form, displaying how many 'cycles' are left before it has completed.
There is also another label that displays how many actions have occurred thus far.
Spawning a new action
The important part is to let all the UI key events to occur, not blocking in the UI thread causing them to queue up.
public void keyPressed(KeyEvent e) {
char keyChar = e.getKeyChar();
System.out.println("KeyChar: " + keyChar);
// Press a to start an Action
if (keyChar == 'a') {
if (!mAction.isRunning()) {
mTotalActions.setText("Ran " + (++mTotalActionsRan) + " actions.");
System.out.println("Starting new Action");
Thread thread = new Thread(new Runnable() {
public void run() {
mAction.run();
}
});
thread.start();
}
}
}
Updates to the UI Thread
If your action performs any kind of updates to the User Interface, it will need to use the SwingUtilities.invokeLater method. This method will queue your code to run in the UI thread. You cannot modify the user interface in a thread other than the UI thread. Also, only use SwingUtilities to update UI components. Any calculations, processing, etc that does not invoke methods on a Component, can be done outside the scope of SwingUtilities.invokeLater.
Full Code Listing
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package stackoverflow_4589538;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
public class Main extends JFrame {
private JLabel mActionLabel;
private JLabel mTotalActions;
private int mTotalActionsRan;
private class MyAction {
private boolean mIsRunning = false;
public void run() {
// Make up a random wait cycle time
final int cycles = new Random().nextInt(100);
for (int i = 0; i < cycles; ++i) {
final int currentCycle = i;
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
mActionLabel.setText("Cycle " + currentCycle + " of " + cycles);
}
});
}
completed();
}
public synchronized void start() {
mIsRunning = true;
}
public synchronized void completed() {
mIsRunning = false;
}
public synchronized boolean isRunning() {
return mIsRunning;
}
}
private MyAction mAction = new MyAction();
public Main() {
setLayout(null);
setBounds(40, 40, 800, 600);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
char keyChar = e.getKeyChar();
System.out.println("KeyChar: " + keyChar);
// Press A to start an Action
if (keyChar == 'a') {
if (!mAction.isRunning()) {
mTotalActions.setText("Ran " + (++mTotalActionsRan) + " actions.");
System.out.println("Starting new Action");
Thread thread = new Thread(new Runnable() {
public void run() {
mAction.run();
}
});
// I had this within the run() method before
// but realized that it is possible for another UI event
// to occur and spawn another Action before, start() had
// occured within the thread
mAction.start();
thread.start();
}
}
}
#Override
public void keyReleased(KeyEvent e) {
}
});
mActionLabel = new JLabel();
mActionLabel.setBounds(10, 10, 150, 40);
mTotalActions = new JLabel();
mTotalActions.setBounds(10, 50, 150, 40);
add(mActionLabel);
add(mTotalActions);
}
public static void main(String[] args) {
new Main().setVisible(true);
}
}
I also noticed that the keyRelease event doesn't occur until after the final keyPress event is processed regardless of when the key was actually released
This depends on the OS you are using. This is the behaviour on Windows (which makes sense to me). On Unix or Mac I believe you get multiple keyPressed, keyReleased events. So you solution should not be based on keyReleased events.
I have a program where the user can press a key to perform an action.
Then you should be using Key Binding, not a KeyListener. Read the section from the Swing tutorial on How to Use Key Bindings for more information.
When the Action is invoked you can then disable it. I'm not sure if this will prevent the KeyStroke from working again or whether you will still need to check the enabled state of the Action. Then when the Action code is finished executing you can re-enable the Action.
Also, this long running code should not execute on the EDT. Read the section from the Swing tutorial on Concurrency for more information about this and for solutions.
You will have to go with option 1. Once you start your longer process, set a boolean of some time to indicate you are working on it and throw out other incoming identical requests. Once you complete the process set the boolean back and allow additional events.
Related
I have an array of strings which I'm trying to display (one by one) as a slideshow in a Java Swing component. I am also trying to add a delay time between the iterations.
I attempted to do this by using a JTextArea, with an action listener added to it. Here is the code I have right now:
private class myActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// A BUNCH OF TEXT PROCESSING
//NOTE: myInfo.getContents() returns an ArrayList<myType>.
Iterator<myType> iterator = myInfo.getContents().iterator();
int i = 0;
while (iterator.hasNext()) {
myTextArea.setText(iterator.next().toString());
// to add time betweeen iterations i wanted to use the thread
// delay method.
}
}
}
My code is not working because JTextArea doesn't have an action listener.
UPDATE
NOTE: Many replies stated that I should use an ActionListener for the JTextArea; However, Eclipse is not showing me that JTextArea has a method called addActionListener.
I'm kind of stuck here, which Java Swing component do you think would be the most suitable in this scenario?
The text in my array may be long, so a one lined label would not be a good choice.
What other alternatives or approaches do I have?
Thank you very much, any help and suggestions are appreciated.
This is basic example is based on the suggestion posted by #Robin
public class TestDisplayString {
public static void main(String[] args) {
new TestDisplayString();
}
public TestDisplayString() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextArea textArea;
private List<String> content;
private Iterator<String> iterator;
public TestPane() {
readText();
setLayout(new BorderLayout());
textArea = new JTextArea(10, 40);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
add(new JScrollPane(textArea));
iterator = content.iterator();
Timer timer = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (iterator.hasNext()) {
textArea.setText(iterator.next());
} else {
((Timer)e.getSource()).stop();
}
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
}
protected void readText() {
content = new ArrayList<>(25);
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/Text.txt")));
String text = null;
while ((text = reader.readLine()) != null) {
if (text.trim().length() > 0) {
content.add(text);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception e) {
}
}
}
}
}
This is the contents of the "Text.txt" file.
How to Use Swing Timers
A Swing timer (an instance of javax.swing.Timer) fires one or more
action events after a specified delay. Don't confuse Swing timers with
the general-purpose timer facility that was added to the java.util
package in release 1.3. This page describes only Swing timers.
In general, we recommend using Swing timers rather than
general-purpose timers for GUI-related tasks because Swing timers all
share the same, pre-existing timer thread and the GUI-related task
automatically executes on the event-dispatch thread. However, you
might use a general-purpose timer if you don't plan on touching the
GUI from the timer, or need to perform lengthy processing.
You can use Swing timers in two ways:
To perform a task once, after a delay.
For example, the tool tip manager uses Swing timers to determine when to show a tool tip and when to hide it.
To perform a task repeatedly.
For example, you might perform animation or update a component that displays progress toward a goal.
Swing timers are very easy to use. When you create the timer, you
specify an action listener to be notified when the timer "goes off".
The actionPerformed method in this listener should contain the code
for whatever task you need to be performed. When you create the timer,
you also specify the number of milliseconds between timer firings. If
you want the timer to go off only once, you can invoke
setRepeats(false) on the timer. To start the timer, call its start
method. To suspend it, call stop.
Note that the Swing timer's task is performed in the event dispatch
thread. This means that the task can safely manipulate components, but
it also means that the task should execute quickly. If the task might
take a while to execute, then consider using a SwingWorker instead of
or in addition to the timer. See Concurrency in Swing for instructions
about using the SwingWorker class and information on using Swing
components in multi-threaded programs.
Let's look at an example of using a timer to periodically update a
component. The TumbleItem applet uses a timer to update its display at
regular intervals. (To see this applet running, go to How to Make
Applets. This applet begins by creating and starting a timer:
timer = new Timer(speed, this); timer.setInitialDelay(pause);
timer.start();
The speed and pause variables represent applet parameters; as
configured on the other page, these are 100 and 1900 respectively, so
that the first timer event will occur in approximately 1.9 seconds,
and recur every 0.1 seconds. By specifying this as the second argument
to the Timer constructor, TumbleItem specifies that it is the action
listener for timer events.
After starting the timer, TumbleItem begins loading a series of images
in a background thread. Meanwhile, the timer events begin to occur,
causing the actionPerformed method to execute:
public void actionPerformed(ActionEvent e) {
//If still loading, can't animate.
if (!worker.isDone()) {
return;
}
loopslot++;
if (loopslot >= nimgs) {
loopslot = 0;
off += offset;
if (off < 0) {
off = width - maxWidth;
} else if (off + maxWidth > width) {
off = 0;
}
}
animator.repaint();
if (loopslot == nimgs - 1) {
timer.restart();
} }
Until the images are loaded, worker.isDone returns false, so timer
events are effectively ignored. The first part of the event handling
code simply sets values that are employed in the animation control's
paintComponent method: loopslot (the index of the next graphic in the
animation) and off (the horizontal offset of the next graphic).
Eventually, loopslot will reach the end of the image array and start
over. When this happens, the code at the end of actionPerformed
restarts the timer. Doing this causes a short delay before the
animation sequence begins again.
Use your ActionListener in combination with a javax.Swing.Timer. The ActionListener assigned to the Timer will be called on regular intervals with the specified delay.
See the timer tutorial for more information
Well, I have been working on a piece of code for almost 2 days now and not able to resolve the issue.
DESIRED BEHAVIOUR
The following code is supposed to display 10 strings one by one (the next replacing the previous one) with a gap of aprox. 200 ms.
q1
q2
q3
...and so on upto q10
This display sequence starts when the user presses ENTER key.
REFLECTED BEHAVIOUR
The screen waits for aprox. 2 sec after pressing and then shows q10.
Some more info
The label stringText changes value during execution (which I found by writing to console) but the same is not updated on screen (JFrame).
The label changes values through click event on a button, everything else remaining same (as much as possible).
The timer is through a while loop - this may not be as per most people's liking, but lets forget it for the time being.
The method displayQuestion(int number) has a few unnecessary lines. I put them all because I was not sure what would work. Actually, nothing worked!
THE CODE
package sush4;
import java.util.Date;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Sush4 {
// Timer control variables
static long holdTimeWord = 200L;
static long elapsedTime = 0L;
// Counter for Strings displayed
static int i = 0;
// Strings in use
static String[] questionStack = {"q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10"};
// UI: String display variables
static JLabel stringText;
static JFrame mainWindow;
// Key binding action object
private static Action userKeyCommand;
/// Display the question
private static void displayQuestion(int number) {
mainWindow.remove(stringText);
stringText.setText(questionStack[number]);
mainWindow.add(stringText);
mainWindow.setVisible(true);
mainWindow.revalidate();
mainWindow.repaint();
}
private static void q120(){
//// Initiate the text
for(i = 0; i < questionStack.length; i++) {
displayQuestion(i);
//// And wait for Word hold time
long startTime = System.currentTimeMillis();
elapsedTime = 0L;
// Now wait for event to happen
while ( (elapsedTime < holdTimeWord) ) {
elapsedTime = (new Date()).getTime() - startTime;
}
}
}
Sush4() {
//// Create the Window
mainWindow = new JFrame("Sush");
mainWindow.setSize(700, 500);
mainWindow.setLayout(new FlowLayout());
//// And add key bindings for user events
userKeyCommand = new UserKeyCommand();
JRootPane rootPane = mainWindow.getRootPane();
rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("ENTER"), "doEnterAction");
rootPane.getActionMap().put("doEnterAction", userKeyCommand);
// Terminate the program when the user closes the application.
mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainWindow.setResizable(false);
//// Add the text label
stringText = new JLabel("Random Text");
mainWindow.add(stringText);
//// Finally, display the frame.
mainWindow.setVisible(true);
}
static class UserKeyCommand extends AbstractAction {
public void actionPerformed( ActionEvent tf ) {
q120();
}
}
public static void main(String[] args) {
// Create the frame on the event dispatching thread.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new Sush4();
}
});
}
}
The timer is through a while loop - this may not be as per most people's liking, but lets forget it for the time being.
Actually we can't forget about this while loop because this is what is causing troubles. See, q120() method is called when you click a button:
static class UserKeyCommand extends AbstractAction {
#Override // don't forget #Override annotation
public void actionPerformed( ActionEvent tf ) {
q120();
}
}
It means this code is executed in the context of the Event Dispatch Thread (EDT). This is a single and special thread where Swing components must be created/updated and event handling (i.e.: action events) must be performed. If we have a loop in this thread waiting for some condition to continue we'll block the EDT and GUI won't be able to repaint itself until the thread is unlocked.
For repetitive tasks (such as the one in your question) consider use a Swing Timer. For heavy tasks with interim results consider use a SwingWorker instead.
I have an array of strings which I'm trying to display (one by one) as a slideshow in a Java Swing component. I am also trying to add a delay time between the iterations.
I attempted to do this by using a JTextArea, with an action listener added to it. Here is the code I have right now:
private class myActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// A BUNCH OF TEXT PROCESSING
//NOTE: myInfo.getContents() returns an ArrayList<myType>.
Iterator<myType> iterator = myInfo.getContents().iterator();
int i = 0;
while (iterator.hasNext()) {
myTextArea.setText(iterator.next().toString());
// to add time betweeen iterations i wanted to use the thread
// delay method.
}
}
}
My code is not working because JTextArea doesn't have an action listener.
UPDATE
NOTE: Many replies stated that I should use an ActionListener for the JTextArea; However, Eclipse is not showing me that JTextArea has a method called addActionListener.
I'm kind of stuck here, which Java Swing component do you think would be the most suitable in this scenario?
The text in my array may be long, so a one lined label would not be a good choice.
What other alternatives or approaches do I have?
Thank you very much, any help and suggestions are appreciated.
This is basic example is based on the suggestion posted by #Robin
public class TestDisplayString {
public static void main(String[] args) {
new TestDisplayString();
}
public TestDisplayString() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextArea textArea;
private List<String> content;
private Iterator<String> iterator;
public TestPane() {
readText();
setLayout(new BorderLayout());
textArea = new JTextArea(10, 40);
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
add(new JScrollPane(textArea));
iterator = content.iterator();
Timer timer = new Timer(1000, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (iterator.hasNext()) {
textArea.setText(iterator.next());
} else {
((Timer)e.getSource()).stop();
}
}
});
timer.setRepeats(true);
timer.setCoalesce(true);
timer.start();
}
protected void readText() {
content = new ArrayList<>(25);
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/Text.txt")));
String text = null;
while ((text = reader.readLine()) != null) {
if (text.trim().length() > 0) {
content.add(text);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception e) {
}
}
}
}
}
This is the contents of the "Text.txt" file.
How to Use Swing Timers
A Swing timer (an instance of javax.swing.Timer) fires one or more
action events after a specified delay. Don't confuse Swing timers with
the general-purpose timer facility that was added to the java.util
package in release 1.3. This page describes only Swing timers.
In general, we recommend using Swing timers rather than
general-purpose timers for GUI-related tasks because Swing timers all
share the same, pre-existing timer thread and the GUI-related task
automatically executes on the event-dispatch thread. However, you
might use a general-purpose timer if you don't plan on touching the
GUI from the timer, or need to perform lengthy processing.
You can use Swing timers in two ways:
To perform a task once, after a delay.
For example, the tool tip manager uses Swing timers to determine when to show a tool tip and when to hide it.
To perform a task repeatedly.
For example, you might perform animation or update a component that displays progress toward a goal.
Swing timers are very easy to use. When you create the timer, you
specify an action listener to be notified when the timer "goes off".
The actionPerformed method in this listener should contain the code
for whatever task you need to be performed. When you create the timer,
you also specify the number of milliseconds between timer firings. If
you want the timer to go off only once, you can invoke
setRepeats(false) on the timer. To start the timer, call its start
method. To suspend it, call stop.
Note that the Swing timer's task is performed in the event dispatch
thread. This means that the task can safely manipulate components, but
it also means that the task should execute quickly. If the task might
take a while to execute, then consider using a SwingWorker instead of
or in addition to the timer. See Concurrency in Swing for instructions
about using the SwingWorker class and information on using Swing
components in multi-threaded programs.
Let's look at an example of using a timer to periodically update a
component. The TumbleItem applet uses a timer to update its display at
regular intervals. (To see this applet running, go to How to Make
Applets. This applet begins by creating and starting a timer:
timer = new Timer(speed, this); timer.setInitialDelay(pause);
timer.start();
The speed and pause variables represent applet parameters; as
configured on the other page, these are 100 and 1900 respectively, so
that the first timer event will occur in approximately 1.9 seconds,
and recur every 0.1 seconds. By specifying this as the second argument
to the Timer constructor, TumbleItem specifies that it is the action
listener for timer events.
After starting the timer, TumbleItem begins loading a series of images
in a background thread. Meanwhile, the timer events begin to occur,
causing the actionPerformed method to execute:
public void actionPerformed(ActionEvent e) {
//If still loading, can't animate.
if (!worker.isDone()) {
return;
}
loopslot++;
if (loopslot >= nimgs) {
loopslot = 0;
off += offset;
if (off < 0) {
off = width - maxWidth;
} else if (off + maxWidth > width) {
off = 0;
}
}
animator.repaint();
if (loopslot == nimgs - 1) {
timer.restart();
} }
Until the images are loaded, worker.isDone returns false, so timer
events are effectively ignored. The first part of the event handling
code simply sets values that are employed in the animation control's
paintComponent method: loopslot (the index of the next graphic in the
animation) and off (the horizontal offset of the next graphic).
Eventually, loopslot will reach the end of the image array and start
over. When this happens, the code at the end of actionPerformed
restarts the timer. Doing this causes a short delay before the
animation sequence begins again.
Use your ActionListener in combination with a javax.Swing.Timer. The ActionListener assigned to the Timer will be called on regular intervals with the specified delay.
See the timer tutorial for more information
In Java, let's say I have a GUI with 2 buttons, Go and Pause.
When I press Go, "Hello" gets printed out over and over again. When I press Pause, "Hello" no longer gets printed to the screen.
Example: User presses Go button. "Hello" gets printed out for 1 minute until the user presses "Pause."
What is the proper way to express this approach in Java? Is it equivalent to my commented pseudocode within the goButton source?
public void actionPerformed(ActionEvent e) {
if(e.getSource() == goButton)
{
// while user has not pressed the pause button
printHello();
}
else if(e.getSource() == pauseButton)
{
pause();
}
}
Thanks
In order to get this to work, in reasonable fashion, you will need a Thread. This is executed in the background until such time as you decide to cancel/pause it.
This is an EXTREMELY basic example. Normally I'd wrap the task and the GUI up in appropriate classes rather then accessing static references, but it gives a basic idea
public class TestHello {
private static HelloTask task;
public static void main(String[] args) {
Thread thread = new Thread((task = new HelloTask()));
thread.setDaemon(true);
thread.start();
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new GridBagLayout());
frame.setSize(200, 200);
frame.setLocationRelativeTo(null);
JButton goButton = new JButton("Go");
JButton stopButton = new JButton("Stop");
goButton.setActionCommand("Go");
stopButton.setActionCommand("Stop");
ActionHandler handler = new ActionHandler();
goButton.addActionListener(handler);
stopButton.addActionListener(handler);
frame.add(goButton);
frame.add(stopButton);
frame.setVisible(true);
}
public static class ActionHandler implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Go")) {
task.start();
} else if (e.getActionCommand().equals("Stop")) {
task.pause();
}
}
}
public static class HelloTask implements Runnable {
private static final Object WAIT_LOCK = new Object();
private boolean dump = false;
public void start() {
synchronized (WAIT_LOCK) {
dump = true;
WAIT_LOCK.notify();
}
}
public void pause() {
synchronized (WAIT_LOCK) {
dump = false;
WAIT_LOCK.notify();
}
}
#Override
public void run() {
while (true) {
while (dump) {
System.out.println("Hello");
}
try {
synchronized (WAIT_LOCK) {
WAIT_LOCK.wait();
}
} catch (Exception e) {
}
}
}
}
}
Some further read:
Java Concurrency
Concurrency in Swing
Caveats
NEVER try and modify the GUI from any thread other then the Event Dispatching Thread.
To have responsive UI you would usually have to run printHello() in separate thread. Then as you do processing in this thread, for example, after every print statement, you check some flag boolean isPaused; and stop execution if it is true. When pause button is clicked you set the value of this flag to true.
You need to implement your loop in a separate thread. Otherwise the GUI will become irresponsive and the user might not be able to click the Pause button at all.
With this threaded approach, you also need a flag which indicates whether or not to print out the message. The printing loop can simply stop executing the thread when the flag is set to no longer print.
what about htis:
boolean flag=true;
public void actionPerformed(ActionEvent e) {
if(e.getSource() == goButton)
{
while(true)
{
printHello();
}
}
else if(e.getSource() == pauseButton)
{
pause();
}
}
You can do this in a few ways the simplest being:
You have a boolean flag, keepPrinting and you set it to true when you push the Go button, false when you push the Pause. Next you have a thread somewhere executing a while loop which will print nothing when keepPrinting is false.
The threading here is really important, without it you're going to have your GUI freeze once the user pushes a button as the program prints hello and happily ignores anything else.
Pseudo Code
//GUI
public ThreadedPrinter greeter;
void ButtonGoPushed(args){
greeter.keepPrinting = true;
}
void ButtonPausePushed(args){
greeter.keepPrinting = false;
}
//ThreadedPrinter
boolean keepPrinting
void run(){
while(true){
if(keepPrinting){
print("Hello");
}
sleep(5); //Make sure that this thread yields if the system doesn't do it automatically
}
The good news about java concurrency versus say C++ is that this will just work, you don't have to worry about the boolean being crazy and inconsistent because in java variable sets are atomic. If you want to do more than just set the variable, make a synchronized method that sets the variable and does anything else you want.
Basically to keep UI responsive such task need to be performed in other thread.
There can be various ways in which you can implement this mechanism in java.
I have used simple mechanism of Runnalbe and volatile flag which ensure that thread exists when you call cancelPrint() method
public void actionPerformed(ActionEvent e) {
if(e.getSource() == goButton)
{
//start the thread here
}
else if(e.getSource() == pauseButton)
{
//call cancel here
}
}
public class HelloPrinter implements Runnable {
volatile boolean cancel = false;
#Override
public void run() {
while (!cancel) {
printHello();
}
}
public void cancelPrint() {
cancel = true;
}
}
I assume you want to do more than just printouts. Take a look at Swing Worker.
It allows you to pretty easily write your GUI-related code that gets executed in the AWT Event Thread and your long-executing code in other thread(s) and pass values back and forth. This will help prevent any GUI lockup issues you might experience.
I need a bit of help with my program here. I have a blocking function waiting in my main thread for the user to click "Enter". Then, when the user hits enter, the keypressed event should fire, which will unblock the blocking function. However, when the program hits the blocking function, it simply freezes up and doesn't register the key pressed event.
So, my question is, is a event a runnable, which is added to a thread whenever the user clicks enter? If so, my code should have worked, right? If this is not the case, and each event is not a separate thread, could anyone enlighten me on how I should fix my problem here?
my blocking function:
public String getInput() {
synchronized(waitObject) {
try {
System.out.println("waiting");
waitObject.wait(); // throws exception, cba to add it here
} catch (Exception ex) {
ex.printStackTrace();
}
}
return(myString);
}
my keylistener code:
public void keyPressed(KeyEvent e) {
System.out.println("key pressed");
char c = e.getKeyChar();
if (c == e.VK_ENTER) {
System.out.println("Enter pressed");
synchronized(waitObject) {
waitObject.notifyAll();
}
}
}
and the function getting the input:
private String getCommand() {
System.out.println("getting command");
CommandField command = new CommandField((JFrame)(this));
command.setPreferredSize(new Dimension(getWidth(), 30));
m_panel.add(command, BorderLayout.NORTH);
validate();
command.requestFocus();
System.out.println(command.getInput());
return null;
}
And this function is called from another keylistener:
public class Listener implements KeyListener {
public void keyPressed(KeyEvent e) {
if (e.getKeyCode() == KeyEvent.VK_F2) {
System.out.println(getCommand());
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
}
OK, getCommand() is called on the event thread which then calls getInput() on the same thread, which then calls Object#wait() on the event thread, so yes you are tying up the event thread and effectively freezing your program.
None of this is needed, and a much easier fix is possible if you code using the concepts of event-driven programming. You don't want to call wait() in a Swing GUI and in your situation don't need to call it, but rather you want to change how your program responds to input based on its state. If you tell us more on the exact behavior you're trying to elicit, we can probably help you find a much better solution.
Edit
Consider using a JOptionPane or a modal JDialog for displaying a "blocking" window that stops the main program until the dialog has been dealt with.
Starting with ImageApp, I added the following key binding in the constructor. It will show() the popup menu when pressing the Enter key. You can change the arbitrary location to suit your usage.
this.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "showPopup");
this.getActionMap().put("showPopup", new AbstractAction("showPopup") {
#Override
public void actionPerformed(ActionEvent e) {
popup.show(ImageApp.this, 42, 42);
}
});
Addendum: To bring up a modal input dialog, so something like this:
this.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "dialog");
this.getActionMap().put("dialog", new AbstractAction("dialog") {
#Override
public void actionPerformed(ActionEvent e) {
String value = JOptionPane.showInputDialog("What?");
System.out.println(value);
}
});