Require assistance on stopping a timer when a slider change has occured - java

I'm trying to create a animation by importing pictures from a sprite sheet and changing the speed using a timer. When I set the speed for the first time, it works perfectly, but anytime after that it wont change the speed. The previous speed will continue playing and I get this error in the output: http://imgur.com/a/sWhmQ
Any help would be appreciated.
Here is what I have so far:
Edit: Found the problem for the timerTask & moved it into the ChangeListener, however, the speed still does not change when the slider moves.
import javax.swing.*;
import javax.swing.event.*;
import java.awt.event.*;
import java.util.Timer;
import java.util.TimerTask;
public class AnimationGUI {
private static int counter = 0;
private static JLabel value = new JLabel("0");
private static JLabel image = new JLabel("");
private static Timer timer = new Timer();
public static void main(String[] args) {
JFrame frame = new JFrame("Animation GUI");
JPanel panel = new JPanel();
JSlider slider = new JSlider(JSlider.HORIZONTAL, 1, 10, 1);
slider.addChangeListener(new Slider());
frame.setVisible(true);
frame.setSize(500, 500);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(panel);
panel.add(slider);
panel.add(value);
panel.add(image);
}
private static class Slider implements ChangeListener {
public void stateChanged(ChangeEvent event) {
JSlider source = (JSlider) event.getSource();
TimerTask task = new TimerTask() {
public void run() {
image.setIcon(new ImageIcon(counter + ".png"));
counter++;
if (counter > 12) {
counter = 0;
}
}
};
if (!source.getValueIsAdjusting()) {
value.setText("" + (int) source.getValue());
int speed = source.getValue() * 100;
timer.scheduleAtFixedRate(task, 0, speed);
}
}
}
}

First recommendation, use a Swing Timer instead of a TimerTask, apart from been self contained and supporting things like stop, start and restart, it's also safe to use for updating the UI from - Swing is not thread safe
Something like...
private static class Slider implements ChangeListener {
private Timer timer;
public Slider() {
timer = new Timer(16, new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
image.setIcon(new ImageIcon(counter + ".png"));
counter++;
if (counter > 12) {
counter = 0;
}
}
});
timer.start()
}
public void stateChanged(ChangeEvent event) {
JSlider source = (JSlider) event.getSource();
if (!source.getValueIsAdjusting()) {
value.setText("" + (int) source.getValue());
int speed = source.getValue() * 100;
timer.setDelay(speed);
}
}
}
as an example
See How to use Timers for more details

I suspect that you need to cancel the existing TimerTask and start a new one with the desired speed.

Related

How to make a pause-able count up timer in Java?

I'm trying to make a timer that will count up from 00h:00m:00s, with the ability to pause and restart the count from its current time.
Heres the solution I currently have: It will always restart the timer from 0 instead of continuing where it left off. Also, for another inexplicable reason, the hours always display as 07 instead of 00. Does anyone know how I could fix these issues, to have it start counting up from its previous value, and display the correct amount of hours elapsed?
private final SimpleDateFormat date = new SimpleDateFormat("KK:mm:ss");
private long startTime = 0;
private final ClockListener clock = new ClockListener();
private final Timer normalTimer = new Timer(53, clock);
startTimerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(startTime == 0) {
startTime = System.currentTimeMillis();
}
else {
startTime += (System.currentTimeMillis() - startTime);
}
normalTimer.start();
}
});
stopTimerButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
normalTimer.stop();
}
});
private void updateClock(){
Date elapsed = new Date(System.currentTimeMillis() - startTime);
timerText.setText(date.format(elapsed));
}
private class ClockListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
updateClock();
}
}
Introduction
Oracle has a helpful tutorial, Creating a GUI With Swing. Skip the Learning Swing with the NetBeans IDE section.
Your code wasn't runnable, so I created the following GUI.
When you press the "Start" button, the timer starts counting. 37 seconds.
2 minutes, 7 seconds.
1 hour, 6 minutes, 11 seconds.
Pressing the "Pause button pauses the count. Pressing the "Restart" button resumes the count. You can pause and resume the count as many times as you want.
Pressing the "Stop" button stops the counter. You can press the "Reset" button to reset the counter before starting again.
Explanation
When creating a Swing application, using the model-view-controller (MVC) pattern helps to separate your concerns and allows you to focus on one part of the application at a time.
Creating the application model made creating the GUI much easier. The application model is made up of one or more plain Java getter/setter classes.
The CountupTimerModel class keeps long fields to hold the duration in milliseconds and the previous duration. This way, I don't have to pause and restart the Swing Timer.
The duration is the difference between the current time and the start time. I use the System.currentTimeMillis() method to calculate the duration.
The GUI is fairly straightforward.
I made the JButton ActionListeners lambdas. I made the TimerListener a separate class to move the code out of that particular lambda.
Code
Here's the complete runnable code. I made the additional classes inner classes so I could post the code as one block.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class CountupTimerGUI implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new CountupTimerGUI());
}
private final CountupTimerModel model;
private JButton resetButton, pauseButton, stopButton;
private JLabel timerLabel;
public CountupTimerGUI() {
this.model = new CountupTimerModel();
}
#Override
public void run() {
JFrame frame = new JFrame("Countup Timer GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(createDisplayPanel(), BorderLayout.NORTH);
frame.add(createButtonPanel(), BorderLayout.SOUTH);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createDisplayPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
Font font = panel.getFont().deriveFont(Font.BOLD, 48f);
timerLabel = new JLabel(model.getFormattedDuration());
timerLabel.setFont(font);
panel.add(timerLabel);
return panel;
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(0, 5, 5, 5));
Font font = panel.getFont().deriveFont(Font.PLAIN, 16f);
resetButton = new JButton("Reset");
resetButton.setFont(font);
panel.add(resetButton);
resetButton.addActionListener(event -> {
model.resetDuration();
timerLabel.setText(model.getFormattedDuration());
});
pauseButton = new JButton("Restart");
pauseButton.setFont(font);
panel.add(pauseButton);
pauseButton.addActionListener(event -> {
String text = pauseButton.getText();
if (text.equals("Pause")) {
model.pauseTimer();
pauseButton.setText("Restart");
} else {
model.startTimer();
pauseButton.setText("Pause");
}
});
Timer timer = new Timer(200,
new CountupListener(CountupTimerGUI.this, model));
stopButton = new JButton("Start");
stopButton.setFont(font);
panel.add(stopButton);
stopButton.addActionListener(event -> {
String text = stopButton.getText();
if (text.equals("Start")) {
model.resetDuration();
model.startTimer();
timer.start();
resetButton.setEnabled(false);
stopButton.setText("Stop");
} else {
model.stopTimer();
timer.stop();
resetButton.setEnabled(true);
stopButton.setText("Start");
}
});
Dimension d = getLargestJButton(resetButton, pauseButton, stopButton);
resetButton.setPreferredSize(d);
pauseButton.setPreferredSize(d);
stopButton.setPreferredSize(d);
pauseButton.setText("Pause");
return panel;
}
private Dimension getLargestJButton(JButton... buttons) {
Dimension largestDimension = new Dimension(0, 0);
for (JButton button : buttons) {
Dimension d = button.getPreferredSize();
largestDimension.width = Math.max(largestDimension.width, d.width);
largestDimension.height = Math.max(largestDimension.height,
d.height);
}
largestDimension.width += 10;
return largestDimension;
}
public JButton getResetButton() {
return resetButton;
}
public JButton getPauseButton() {
return pauseButton;
}
public JButton getStopButton() {
return stopButton;
}
public JLabel getTimerLabel() {
return timerLabel;
}
public class CountupListener implements ActionListener {
private final CountupTimerGUI view;
private final CountupTimerModel model;
public CountupListener(CountupTimerGUI view, CountupTimerModel model) {
this.view = view;
this.model = model;
}
#Override
public void actionPerformed(ActionEvent event) {
model.setDuration();
view.getTimerLabel().setText(model.getFormattedDuration());
}
}
public class CountupTimerModel {
private boolean isRunning;
private long duration, previousDuration, startTime;
public CountupTimerModel() {
resetDuration();
}
public void resetDuration() {
this.duration = 0L;
this.previousDuration = 0L;
this.isRunning = true;
}
public void startTimer() {
this.startTime = System.currentTimeMillis();
this.isRunning = true;
}
public void pauseTimer() {
setDuration();
this.previousDuration = duration;
this.isRunning = false;
}
public void stopTimer() {
setDuration();
this.isRunning = false;
}
public void setDuration() {
if (isRunning) {
this.duration = System.currentTimeMillis() - startTime
+ previousDuration;
}
}
public String getFormattedDuration() {
int seconds = (int) ((duration + 500L) / 1000L);
int minutes = seconds / 60;
int hours = minutes / 60;
StringBuilder builder = new StringBuilder();
if (hours > 0) {
builder.append(hours);
builder.append(":");
}
minutes %= 60;
if (hours > 0) {
builder.append(String.format("%02d", minutes));
builder.append(":");
} else if (minutes > 0) {
builder.append(minutes);
builder.append(":");
}
seconds %= 60;
if (hours > 0 || minutes > 0) {
builder.append(String.format("%02d", seconds));
} else {
builder.append(seconds);
}
return builder.toString();
}
}
}

Why is my thread not working properly in Swing?

I am printing simple value to append JTextArea using simple for loop, and when I run it, it's properly Run if I print value in console output...
But if I append JTextArea and print value in the text area, they are appended all after whole program run.
public class SwingThread {
private JFrame frame;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SwingThread window = new SwingThread();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public SwingThread() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollPane = new JScrollPane();
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
JTextArea textArea = new JTextArea();
scrollPane.setViewportView(textArea);
JButton btnNewButton = new JButton("New button");
scrollPane.setColumnHeaderView(btnNewButton);
btnNewButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
try
{
for(int i = 0 ; i <= 5 ; i++)
{
textArea.append("Value "+i+"\n");
System.out.println("Value is" + i);
Thread.sleep(1000);
}
}
catch(Exception e)
{
System.out.println("Error : "+e);
}
}
});
}
}
I want to append one by one, but it was appended after the whole program runs.
Your problem is with your use of Thread.sleep, since when you call this on the Swing event thread (or EDT for Event Dispatch Thread) as you are doing, it will put the entire Swing event thread to sleep. When this happens the actions of this thread cannot be performed, including painting the GUI (updating it) and interacting with the user, and this will completely freeze your GUI -- not good. The solution in this current situation is to use a Swing Timer as a pseudo-loop. The Timer creates a loop within a background thread and guarantees that all code within its actionPerformed method will be called on the Swing event thread, a necessity here since we don't want to append to the JTextArea off of this thread.
Also as others have noted, if all you want to do is to perform a repeated action with delay in Swing, then yes, use this Swing Timer. If on the other hand you wish to run a long-running bit of code in Swing, then again this code will block the EDT and will freeze your program. For this situation use a background thread such as one supplied by a SwingWorker. Please check out Lesson: Concurrency in Swing for more on this.
e.g.,
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// delay between timer ticks: 1000
int timerDelay = 1000;
new Timer(timerDelay, new ActionListener() {
private int counter = 0;
#Override
public void actionPerformed(ActionEvent e) {
// timer's stopping condition
if (counter >= MAX_VALUE) { // MAX_VALUE is a constant int = 5
((Timer) e.getSource()).stop();
} else {
textArea.append("Value " + counter + "\n");
}
counter++; // increment timer's counter variable
}
}).start();
}
});
The whole thing:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.*;
import javax.swing.*;
public class SwingThread2 {
protected static final int MAX_VALUE = 5; // our constant
private JFrame frame;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SwingThread2 window = new SwingThread2();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public SwingThread2() {
initialize();
}
private void initialize() {
frame = new JFrame();
// frame.setBounds(100, 100, 450, 300); // avoid this
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollPane = new JScrollPane();
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
JTextArea textArea = new JTextArea(15, 40);
scrollPane.setViewportView(textArea);
JButton btnNewButton = new JButton("New button");
scrollPane.setColumnHeaderView(btnNewButton);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// delay between timer ticks: 1000
int timerDelay = 1000;
new Timer(timerDelay, new ActionListener() {
private int counter = 0;
#Override
public void actionPerformed(ActionEvent e) {
// timer's stopping condition
if (counter >= MAX_VALUE) { // MAX_VALUE is a constant int = 5
((Timer) e.getSource()).stop();
} else {
textArea.append("Value " + counter + "\n");
}
counter++; // increment timer's counter variable
}
}).start();
}
});
// better to avoid setting sizes but instead to
// let the components size themselves vis pack
frame.pack();
frame.setLocationRelativeTo(null);
}
}
Just for further information, here is an example of the same program above that uses a SwingWorker to perform a long running action, and then update a JProgressBar with this action. The worker is quite simple, and simply uses a while loop to advance a counter variable by a bounded random amount. It then transmits uses this value to update its own progress property (a value that can only be from 0 to 100, and so in other situations, the value will need to be normalized to comply with this). I attach a PropertyChangeListener to the worker, and this is notified on the Swing event thread whenever the worker's progress value changes and also whenever the SwingWorker changes state, such as when it is done operating. In the latter situation, the worker's StateValue becomes StateValue.DONE. The listener then updates the GUI accordingly. Please ask if any questions.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.*;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import javax.swing.*;
public class SwingThread2 {
protected static final int MAX_VALUE = 5; // our constant
private JFrame frame;
private JProgressBar progressBar = new JProgressBar();
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SwingThread2 window = new SwingThread2();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public SwingThread2() {
initialize();
}
private void initialize() {
frame = new JFrame();
// frame.setBounds(100, 100, 450, 300); // avoid this
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JScrollPane scrollPane = new JScrollPane();
frame.getContentPane().add(scrollPane, BorderLayout.CENTER);
JTextArea textArea = new JTextArea(15, 40);
scrollPane.setViewportView(textArea);
JButton btnNewButton = new JButton("New button");
scrollPane.setColumnHeaderView(btnNewButton);
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
// delay between timer ticks: 1000
int timerDelay = 1000;
new Timer(timerDelay, new ActionListener() {
private int counter = 0;
#Override
public void actionPerformed(ActionEvent e) {
// timer's stopping condition
if (counter >= MAX_VALUE) { // MAX_VALUE is a constant
// int = 5
((Timer) e.getSource()).stop();
} else {
textArea.append("Value " + counter + "\n");
}
counter++; // increment timer's counter variable
}
}).start();
}
});
progressBar.setStringPainted(true);
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.LINE_AXIS));
bottomPanel.add(new JButton(new MyAction("Press Me")));
bottomPanel.add(progressBar);
frame.getContentPane().add(bottomPanel, BorderLayout.PAGE_END);
// better to avoid setting sizes but instead to
// let the components size themselves vis pack
frame.pack();
frame.setLocationRelativeTo(null);
}
private class MyAction extends AbstractAction {
public MyAction(String name) {
super(name);
int mnemonic = (int) name.charAt(0);
putValue(MNEMONIC_KEY, mnemonic);
}
public void actionPerformed(ActionEvent e) {
progressBar.setValue(0);
setEnabled(false);
MyWorker myWorker = new MyWorker();
myWorker.addPropertyChangeListener(new WorkerListener(this));
myWorker.execute();
}
}
private class WorkerListener implements PropertyChangeListener {
private Action action;
public WorkerListener(Action myAction) {
this.action = myAction;
}
#Override
public void propertyChange(PropertyChangeEvent evt) {
if ("progress".equals(evt.getPropertyName())) {
int progress = (int) evt.getNewValue();
progressBar.setValue(progress);
} else if ("state".equals(evt.getPropertyName())) {
if (evt.getNewValue() == SwingWorker.StateValue.DONE) {
action.setEnabled(true);
#SuppressWarnings("rawtypes")
SwingWorker worker = (SwingWorker) evt.getSource();
try {
// always want to call get to trap and act on
// any exceptions that the worker might cause
// do this even though get returns nothing
worker.get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
}
}
}
private class MyWorker extends SwingWorker<Void, Void> {
private static final int MULTIPLIER = 80;
private int counter = 0;
private Random random = new Random();
#Override
protected Void doInBackground() throws Exception {
while (counter < 100) {
int increment = random.nextInt(10);
Thread.sleep(increment * MULTIPLIER);
counter += increment;
counter = Math.min(counter, 100);
setProgress(counter);
}
return null;
}
}
}

Making a countdown timer that doesn't interrupt the entire program?

So I'm trying to make a reaction game where you press start button, a hidden timer that will countdown to zero from a random number between 1 & 10 seconds. Most answer regarding java timers recommend using
Thread.sleep(1000);
However this interrupts the entire program while I just wants it to countdown. How should I solve this?
After pressing start and the program has counted down from a random number. The blue icon (entire code below) will turn red and then you're supposed to press it and it will display the time it took for you to press it.
Code is focus:
public void countDown() throws InterruptedException {
int random = r.nextInt((10000 - 1000) + 1) + 1000;
while(random >= 0){
Thread.sleep(1000);
random -= 1000;
}
if (random <= 0) {
button_1.setIcon(img_react);
repaint();
}
}
Image files used:
http://imgur.com/DjI8Udr
http://imgur.com/XKQW6DI
Entire code:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.Timer;
import java.util.*;
public class Interface extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
ImageIcon img_idle = new ImageIcon("img_idle.png");
ImageIcon img_react = new ImageIcon("img_react.png");
JButton button_1 = new JButton(img_idle);
JButton start = new JButton("Start");
Random r = new Random();
public Interface() {
super("Simple Reaction Game");
setSize(180, 350);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
Container contentArea = getContentPane();
contentArea.setBackground(Color.white);
FlowLayout flowManager = new FlowLayout();
contentArea.setLayout(flowManager);
button_1.addActionListener(this);
start.addActionListener(this);
contentArea.add(button_1);
contentArea.add(start);
setContentPane(contentArea);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == start) {
try {
countDown();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
public void countDown() throws InterruptedException {
Thread t = new Thread();
int random = r.nextInt((10000 - 1000) + 1) + 1000;
while(random >= 0){
t.sleep(1000);
random -= 1000;
}
if (random <= 0) {
button_1.setIcon(img_react);
repaint();
}
}
public static void main(String args[]) {
new Interface();
}
}
You can't just use Thread.sleep(), it won't work as you think it does. Instead, you can use javax.swing.Timer which is made to do what you're trying to do.
Some notes from the docs (if you didn't bother reading it):
Timers perform their waiting using a single, shared thread.
Timers can safely perform operations on Swing components.
Timers can safely perform operations on Swing components.
The javax.swing.Timer has two features that can make it a little easier to use with GUIs.
I've modified an example from here to show how you can adapt it to your needs. It's using your random generated number which is generated each time the timer is finished and you press "start".
import java.awt.*;
import java.awt.event.*;
import java.text.SimpleDateFormat;
import javax.swing.*;
import javax.swing.UnsupportedLookAndFeelException;
import java.util.Random;
public class Interface {
public static void main(String[] args) {
new Interface();
}
public Interface() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private Timer timer;
private long startTime = -1;
private long duration;
private JLabel label;
private JButton start;
public TestPane() {
start = new JButton("Start");
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
timer = new Timer(10, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (startTime < 0) {
startTime = System.currentTimeMillis();
}
long now = System.currentTimeMillis();
long clockTime = now - startTime;
if (clockTime >= duration) {
clockTime = duration;
timer.stop();
}
SimpleDateFormat df = new SimpleDateFormat("mm:ss:SSS");
label.setText(df.format(duration - clockTime));
}
});
timer.setInitialDelay(0);
start.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (!timer.isRunning()) {
duration = new Random().nextInt((10000 - 1000) + 1) + 1000;
startTime = -1;
timer.start();
}
}
});
label = new JLabel("...");
add(label);
add(start);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 250);
}
}
}
I would suggest a different architecture. Why do you think you need to "count down" anything?!
Meaning: all you care about is that you want to do "something" after a random period of time; so something like this (using pseudo-code) might be easier in the end:
now = ... get current time
then = now + random value
schedule the Swing timer to sent some Event X "then"
And simply have some code that that reacts to incoming X events.

Updating textArea inside iteration

i have a fun project where i need to change the content of a text area inside a iteration.
Its a character, a "projectile", moving trought a string. The string is updated and sent to the textArea inside the iteration, and the iteration stops when the character reaches a wall.
But my textArea only updates (visually) when i leave the iteration. While im inside it, textArea freezes, as if its waiting for the iteration, even with Thread.sleep() inside it.
I made an MVCE exemplifing the problem bellow, notice the text only shows after the iteration, i want it to apper in every step of the while.
public class GUIProblem extends JFrame{
public GUIProblem() {
setSize(640, 480);
JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.CENTER);
final JTextArea textArea = new JTextArea();
textArea.setRows(10);
textArea.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
int i = 0;
while(i < 10){
textArea.setText("this text only appears after the iteration, i want it to appear in each step of the iteration!");
System.out.println("iterating..." + i++);
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
textArea.setColumns(30);
panel.add(textArea);
}
/**
*
*/
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
GUIProblem gui = new GUIProblem( );
gui.setVisible(true);
}
});
JOptionPane.showMessageDialog(null, "Click the textArea!");
}
}
You've a classic Swing threading issue where you stop the Swing event thread in its tracks with your iteration and its Thread.sleep() calls. The solution is the same as for similar questions: use a Swing Timer or background thread such as a SwingWorker. In your case, use the Timer.
For example, since you posted an MCVE
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class GUIProblem extends JFrame {
public GUIProblem() {
// setSize(640, 480);
JPanel panel = new JPanel();
getContentPane().add(panel, BorderLayout.CENTER);
final JTextArea textArea = new JTextArea(20, 50);
textArea.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent mEvt) {
int i = 0;
int timerDelay = 200;
new Timer(timerDelay, new ActionListener() {
int count = 0;
private final int MAX_COUNT = 10;
#Override
public void actionPerformed(ActionEvent e) {
if (count >= MAX_COUNT) {
((Timer) e.getSource()).stop(); // stop the timer
return;
}
textArea.append("Count is: " + count + "\n");
count++;
}
}).start();
}
});
panel.add(new JScrollPane(textArea));
}
/**
*
*/
private static final long serialVersionUID = 1L;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
GUIProblem gui = new GUIProblem();
gui.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
gui.pack();
gui.setLocationRelativeTo(null);
gui.setVisible(true);
}
});
JOptionPane.showMessageDialog(null, "Click the textArea!");
}
}

bring JInternalFrame to the front

I have a JDesktopPane which contains a number of JInternalFrames. I'd like to be able to bring any JInternalFrame to the front, overlaying any other active frames. I found a number of code samples to do this, but none seem to work - the frame does NOT go on top of other active JInternalFrames. E.g.
public static void moveToFront(final JInternalFrame fr) {
if (fr != null) {
processOnSwingEventThread(new Runnable() {
public void run() {
fr.moveToFront();
fr.setVisible(true);
try {
fr.setSelected(true);
if (fr.isIcon()) {
fr.setIcon(false);
}
fr.setSelected(true);
} catch (PropertyVetoException ex) {
ex.printStackTrace();
}
fr.requestFocus();
fr.toFront();
}
});
}
}
According to the API toFront or moveToFront should work (though toFront looks to be the better of the two from my reading of the API). Are these JInternalFrames sitting in a JDesktopPane? According to your post it seems they are. I wonder if the error lies elsewhere.
Consider creating and posting an SSCCE (please click on the link), a small compilable, runnable program that demonstrates your best attempt at solving this. Then we can inspect your code, run it, modify it and best be able to help you fix it.
Here is my example of an SSCCE:
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.util.Random;
import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class InternalFrameToFront extends JPanel {
private static final int FRAME_MAX = 21;
private static final int DT_WIDTH = 700;
private static final int DT_HEIGHT = 500;
private static final Dimension DESKTOP_SIZE = new Dimension(DT_WIDTH, DT_HEIGHT);
private static final int IF_WIDTH = 150;
private static final int IF_HEIGHT = 100;
private static final Dimension INT_FRAME_SIZE = new Dimension(IF_WIDTH, IF_HEIGHT);
private Random random = new Random();
private JInternalFrame[] internalFrames = new JInternalFrame[FRAME_MAX];
public InternalFrameToFront() {
JDesktopPane desktop = new JDesktopPane();
desktop.setPreferredSize(DESKTOP_SIZE);
for (int i = 0; i < internalFrames.length; i++) {
JInternalFrame intFrame = new JInternalFrame("Frame Number " + i);
intFrame.setSize(INT_FRAME_SIZE);
int x = random.nextInt(DT_WIDTH - IF_WIDTH);
int y = random.nextInt(DT_HEIGHT - IF_HEIGHT);
intFrame.setLocation(x, y);
intFrame.setVisible(true);
desktop.add(intFrame);
internalFrames[i] = intFrame;
}
JSlider slider = new JSlider(0, FRAME_MAX - 1, 0);
slider.setMajorTickSpacing(5);
slider.setMinorTickSpacing(1);
slider.setPaintLabels(true);
slider.setPaintTicks(true);
JPanel sliderPanel = new JPanel();
sliderPanel.add(slider);
slider.addChangeListener(new ChangeListener() {
public void stateChanged(ChangeEvent ce) {
JSlider slider = (JSlider) ce.getSource();
if (!slider.getValueIsAdjusting()) {
int value = slider.getValue();
internalFrames[value].toFront();
}
}
});
setLayout(new BorderLayout());
add(desktop, BorderLayout.CENTER);
add(sliderPanel, BorderLayout.SOUTH);
}
private static void createAndShowUI() {
JFrame frame = new JFrame("InternalFrameToFront");
frame.getContentPane().add(new InternalFrameToFront());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}

Categories