Stopping a thread by a swing button - java

I made a simple program which just tracks the co ordinates of the mouse cursor - it works fine, all I want do is start / stop it with a button.
So far the button starts the thread well, what is the best way which I can safely stop the thread? This is because I may add a facility to write the coordinates to a text file in the future.
Do I make a boolean which makes the thread run only when it is true or something like that? Because I tried to edit the trigger boolean but it had no affect what so ever.
The code as it is :
The class running the thread
public class tester {
static int startTime = (int) System.currentTimeMillis();
static boolean trigger = false;
static JLabel label = new JLabel();
static JLabel status = new JLabel();
static mouseLocate msl = new mouseLocate();
static JButton startButton = new JButton("Begin tracking");
static JButton stopButton = new JButton("Stop Tracker");
static Thread myThread = new Thread(new mouseLocate());
public static void main(String[] args) {
JFrame frame = new JFrame("Mouse Grabber");
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500, 100);
JPanel panel = new JPanel();
frame.add(panel);
panel.add(startButton);
startButton.addActionListener(new startAction());
panel.add(label);
panel.add(status);
}
static class startAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
if (trigger == false) {
trigger = true;
msl.setTrigger(trigger);
//label.setText("Trigger Active" + msl.isTrigger());
startButton.setText("Continue Tracking");
} else if (trigger == true) {
trigger = false;
//msl.setTrigger(trigger);
label.setText("Trigger Inactive");
startButton.setText("Stop Tracking");
}
} catch (Exception exp) {
System.out.println("EXCEPTION CAUGHT " + e);
}
//RUN
myThread.start();
}
}
The mouse locate class:
public class mouseLocate implements Runnable {
private boolean trigger = false;
private int startTime = (int) System.currentTimeMillis();
static String status = "";
public void run() {
int x, y;
while (mouseGrabber.trigger = true) {
try {
PointerInfo mouseLocation = MouseInfo.getPointerInfo();
x = mouseLocation.getLocation().x;
y = mouseLocation.getLocation().y;
System.out.println("X:" + x + " Y:" + y + " Elapsed time: "
+ (((int) System.currentTimeMillis() - startTime) / 100));
} catch (Exception e) {
System.out.println("Exception caught : " + e);
}
}
}
public int getStartTime() {
return startTime;
}
public void setStartTime(int startTime) {
this.startTime = startTime;
}
public boolean isTrigger() {
return trigger;
}
public void setTrigger(boolean trigger) {
this.trigger = trigger;
}
public static String getStatus() {
return status;
}
public static void setStatus(String status) {
mouseLocate.status = status;
}
}
Thank you for any help I really appreciate it.

There is no stopThread() api on java anymore. You should set a flag as volatile, and your stop thread button just set flag variable value.
public volatile boolean flag;
public void run() {
while(flag) {
// Get coordinate or whatever you want
}
}

public volatile boolean isShutingDown;
public void run() {
while(!isShutingDown) {
}
}
call shutDown() method, when you need to stop
public void shutDown(){
isShutingDown = true
}

Related

Java simultaneous execution

I am trying execute two jobs simultaneously. One of the things that I am trying to do is displaying a count up timer and the other one is moving the ball.
This is where I create the timer and also call the moveBall method
button.addChangeListener(new ChangeListener() {
int start = 0;
public void stateChanged(ChangeEvent e) {
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
timeValue.setText(++start + " sec");
}
};
timer = new Timer(1000, taskPerformer);
timer.start();
ball.moveBall();
}
});
This is my moveBall method
public void moveBall() {
Thread ball = new Thread() {
double counter = 0;
int t = (int) (2 * Vy / 9.8);
public void run() {
try {
while (t >= 0) {
// calculate Vx and Vy
Ball.this.setX(Ball.this.getX() + Vx);
Ball.this.setY(Ball.this.getY() - Vy);
counter += 50;
if (counter == 1000) {
t--;
counter = 0;
}
paintingComponent.repaint();
Thread.sleep(20);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
ball.start();
}
When I execute the above code the label for displaying the time passed is not changing at all during the ball is moving and when the movement is over it takes the last number that it supposed to take.
This is a example two executions of two threads, Java simultaneous execution
public class ThreadExecutor extends Thread {
private String name;
private int executionCount;
public ThreadExecutor(final String name, final int executionCount) {
this.name = name;
this.executionCount = executionCount;
}
#Override
public void run() {
int count = 1;
while (count <= executionCount) {
System.out.println("Executing thread ".concat(name).concat(" : ") + count);
count++;
}
}
}
public class Main {
public static void main(String args[]) {
final ThreadExecutor one = new ThreadExecutor("One", 1);
final ThreadExecutor two = new ThreadExecutor("Two", 2);
one.start();
two.start();
}
}

JFrame freezes when button is pressed and operations from the other Class are ran [duplicate]

I'm writing a program that constantly pings a server. I wrote the code to check it once and put the ping in a JLabel and put it in a method called setPing().
Here is my code
private void formWindowOpened(java.awt.event.WindowEvent evt) {
setPing();
}
That worked but only did it once, so I did:
private void formWindowOpened(java.awt.event.WindowEvent evt) {
for(;;){
setPing();
}
}
But this doesn't even work for the first time.
I didnt put the setPing method because it was too long so here it is:
public String setPing(){
Runtime runtime = Runtime.getRuntime();
try{
Process process = runtime.exec("ping lol.garena.com");
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null) {
int i = 0;
i = line.indexOf("Average");
if(i > 0){
String finalPing = "";
line.toCharArray();
try
{
finalPing = "";
for(int x = i; x < i + 17; x++)
{
finalPing = finalPing + (line.charAt(x));
}
}catch(IndexOutOfBoundsException e)
{
try
{
finalPing = "";
for(int x = i; x < i + 16; x++)
{
finalPing = finalPing + (line.charAt(x));
}
}catch(IndexOutOfBoundsException f)
{
try
{
finalPing = "";
for(int x = i; x < i + 15; x++)
{
finalPing = finalPing + (line.charAt(x));
}
}catch(IndexOutOfBoundsException g){}
}
}
String final1Ping = finalPing.replaceAll("[^0-9]", "");
return final1Ping;
}
}
}catch(IOException e){
}
return "";
}
UPDATE
Just in case this is important, Im using netbeans. I created a form and put this code in the formWindowOpened evt instead of calling it in main:
private void formWindowOpened(java.awt.event.WindowEvent evt) {
ActionListener timerListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new PingWorker().execute();
}
};
Timer timer = new Timer(1000, timerListener);
timer.start();
jLabel1.setText(label.getText());
timer.stop();
// TODO add your handling code here:
}
class PingWorker extends SwingWorker {
int time;
#Override
protected Object doInBackground() throws Exception {
time = pingTime("lol.garena.com");
return new Integer(time);
}
#Override
protected void done() {
label.setText("" + time);
}
};
public JComponent getUI() {
return label;
}
public static int pingTime(String hostnameOrIP) {
Socket socket = null;
long start = System.currentTimeMillis();
try {
socket = new Socket(hostnameOrIP, 80);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
}
}
}
long end = System.currentTimeMillis();
return (int) (end - start);
}
Use a Swing Timer for repeating tasks & a SwingWorker for long running tasks. E.G. of both below - it uses a Timer to repeatedly perform a 'long running' task (a ping) in a SwingWorker.
See Concurrency in Swing for more details on the Event Dispatch Thread and doing long running or repeating tasks in a GUI.
This code combines a long running task ('pinging' a server) using SwingWorker invoked from a repeating task (updating the JLabel repeatedly with the times) using a Swing based Timer.
import java.awt.event.*;
import javax.swing.*;
import java.net.Socket;
public class LabelUpdateUsingTimer {
static String hostnameOrIP = "stackoverflow.com";
int delay = 5000;
JLabel label = new JLabel("0000");
LabelUpdateUsingTimer() {
label.setFont(label.getFont().deriveFont(120f));
ActionListener timerListener = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
new PingWorker().execute();
}
};
Timer timer = new Timer(delay, timerListener);
timer.start();
JOptionPane.showMessageDialog(
null, label, hostnameOrIP, JOptionPane.INFORMATION_MESSAGE);
timer.stop();
}
class PingWorker extends SwingWorker {
int time;
#Override
protected Object doInBackground() throws Exception {
time = pingTime();
return new Integer(time);
}
#Override
protected void done() {
label.setText("" + time);
}
};
public static int pingTime() {
Socket socket = null;
long start = System.currentTimeMillis();
try {
socket = new Socket(hostnameOrIP, 80);
} catch (Exception weTried) {
} finally {
if (socket != null) {
try {
socket.close();
} catch (Exception weTried) {}
}
}
long end = System.currentTimeMillis();
return (int) (end - start);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
new LabelUpdateUsingTimer();
}
};
SwingUtilities.invokeLater(r);
}
}
You could use a Thread. The problem is you are blocking the main thread, thereby blocking your program. To get around this, start a background Thread to update components repeatedly.
(Note: you need to update GUI components on the EDT, so use SwingUtilities.invokeLater)
(new Thread((new Runnable(){
#Override
public void run(){
while(true){
SwingUtilities.invokeLater(new Runnable(){
#Override
public void run(){
refToJLabel.setText(Math.random());
}
});
}
}
}))).start();

JSlider issue audio player

I am trying to build an audio player with an integrated JSlider, which updates the interface every microsecond.
In order to do so I am using the following:
sliderTime.setMinimum(0);
sliderTime.setMaximum((int) audioClip.getMicrosecondPosition(););
I have the feeling that this is not the best implementation out there (any suggestions to improve it is highly appreciated)
By the way, the issue I am facing is that for the first second the JSlider does not update.
Please find MCVE below:
It plays only wav uncompressed files
Main
public class Main
{
public static void main(final String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
JFrame f = new JFrame();
PlayerView pw = new PlayerView();
Border border = new EmptyBorder(15,15,15,15);
pw.setBorder(border);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().setLayout(new BorderLayout());
f.getContentPane().add(pw, BorderLayout.CENTER);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
});
}
}
AudioPlayer
public class AudioPlayer implements LineListener
{
private SimpleDateFormat dateFormater = new SimpleDateFormat("HH:mm:ss.SSS");
private TimeZone timeZone = Calendar.getInstance().getTimeZone();
public static final int REWIND_IN_MICROSECONDS = 3000000;
public static final int FORWARD_IN_MICROSECONDS = 3000000;
private boolean playCompleted;
private boolean isStopped;
private boolean isPaused;
private boolean isRewinded;
private boolean isForwarded;
private Clip audioClip;
public Clip getAudioClip()
{
return audioClip;
}
public void load(String audioFilePath) throws UnsupportedAudioFileException, IOException, LineUnavailableException
{
File encodedFile = new File(audioFilePath);
AudioInputStream pcmStream = AudioSystem.getAudioInputStream(encodedFile);
AudioFormat format =pcmStream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
audioClip = (Clip) AudioSystem.getLine(info);
audioClip.addLineListener(this);
audioClip.open(pcmStream);
}
public long getClipMicroSecondLength()
{
return audioClip.getMicrosecondLength();
}
public long getClipMicroSecondPosition()
{
return audioClip.getMicrosecondPosition();
}
public String getClipLengthString()
{
long yourmilliseconds = audioClip.getMicrosecondLength() / 1_000;
Date resultdate = new Date(yourmilliseconds);
dateFormater.setTimeZone(TimeZone.getTimeZone(timeZone.getDisplayName(false, TimeZone.SHORT)));
return dateFormater.format(resultdate);
}
public void play() throws IOException
{
audioClip.start();
playCompleted = false;
isStopped = false;
while (!playCompleted)
{
try
{
Thread.sleep(30);
}
catch (InterruptedException ex)
{
if (isStopped)
{
audioClip.stop();
break;
}
else if (isPaused)
{
audioClip.stop();
}
else if (isRewinded)
{
if( audioClip.getMicrosecondPosition() <= REWIND_IN_MICROSECONDS)
{
audioClip.setMicrosecondPosition(0);
isRewinded =false;
}
else
{
audioClip.setMicrosecondPosition(audioClip.getMicrosecondPosition() - REWIND_IN_MICROSECONDS);
isRewinded =false;
}
}
else if (isForwarded)
{
if((audioClip.getMicrosecondLength() - audioClip.getMicrosecondPosition()) >= FORWARD_IN_MICROSECONDS)
{
audioClip.setMicrosecondPosition(audioClip.getMicrosecondPosition() + FORWARD_IN_MICROSECONDS);
isForwarded =false;
}
else
{
audioClip.stop();
isForwarded =false;
}
}
else
{
audioClip.start();
}
}
}
audioClip.close();
}
public void stop()
{
isStopped = true;
}
public void pause()
{
isPaused = true;
}
public void resume()
{
isPaused = false;
}
public void rewind()
{
isRewinded = true;
}
public void forward()
{
isForwarded = true;
}
#Override
public void update(LineEvent event)
{
Type type = event.getType();
if (type == Type.STOP)
{
if (isStopped || !isPaused)
{
playCompleted = true;
}
}
}
}
PlayingTimer
public class PlayingTimer extends Thread
{
private SimpleDateFormat dateFormater = new SimpleDateFormat("HH:mm:ss.SSS");
private TimeZone timeZone = Calendar.getInstance().getTimeZone();
private boolean isRunning = false;
private boolean isPause = false;
private boolean isReset = false;
private boolean isRewinded = false;
private boolean isForwarded = false;
private long startTime;
private long pauseTime;
private long rewindTime;
private long forwardTime;
private JLabel labelRecordTime;
private JSlider slider;
private Clip audioClip;
public void setAudioClip(Clip audioClip)
{
this.audioClip = audioClip;
}
public PlayingTimer(JLabel labelRecordTime, JSlider slider)
{
this.labelRecordTime = labelRecordTime;
this.slider = slider;
dateFormater.setTimeZone(TimeZone.getTimeZone(timeZone.getDisplayName(false, TimeZone.SHORT)));
}
public void run()
{
isRunning = true;
startTime = System.currentTimeMillis();
while (isRunning)
{
try
{
Thread.sleep(30);
if (!isPause)
{
if (audioClip != null && audioClip.isRunning())
{
long currentMicros = audioClip.getMicrosecondPosition();
// Compute the progress as a value between 0.0 and 1.0
double progress =
(double)currentMicros / audioClip.getMicrosecondLength();
// Compute the slider value to indicate the progress
final int sliderValue = (int)(progress * slider.getMaximum());
// Update the slider with the new value, on the Event Dispatch Thread
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
labelRecordTime.setText(toTimeString());
slider.setValue(sliderValue);
}
});
}
}
else
{
pauseTime += 30;
}
}
catch (InterruptedException ex)
{
if (isReset)
{
slider.setValue(0);
labelRecordTime.setText("00:00:00.000");
isRunning = false;
break;
}
if (isRewinded)
{
if( audioClip.getMicrosecondPosition() <= AudioPlayer.REWIND_IN_MICROSECONDS)
{
//go back to start
rewindTime += audioClip.getMicrosecondPosition() / 1_000;
}
else
{
rewindTime += 3000;
}
isRewinded =false;
}
if (isForwarded)
{
if((audioClip.getMicrosecondLength()- audioClip.getMicrosecondPosition()) <= AudioPlayer.FORWARD_IN_MICROSECONDS)
{
forwardTime -= (audioClip.getMicrosecondLength()- audioClip.getMicrosecondPosition())/1_000;
}
else
{
forwardTime -= 3000;
}
isForwarded=false;
}
}
}
}
public void reset()
{
isReset = true;
isRunning = false;
}
public void rewind()
{
isRewinded = true;
}
public void forward()
{
isForwarded = true;
}
public void pauseTimer()
{
isPause = true;
}
public void resumeTimer()
{
isPause = false;
}
private String toTimeString()
{
long now = System.currentTimeMillis();
Date resultdate = new Date(now - startTime - pauseTime - rewindTime - forwardTime);
return dateFormater.format(resultdate);
}
}
PlayerView
public class PlayerView extends JPanel implements ActionListener
{
private static final int BUTTON_HEIGTH =60;
private static final int BUTTON_WIDTH =120;
private AudioPlayer player = new AudioPlayer();
private Thread playbackThread;
private PlayingTimer timer;
private boolean isPlaying = false;
private boolean isPause = false;
private String audioFilePath;
private String lastOpenPath;
private JLabel labelFileName;
private JLabel labelTimeCounter;
private JLabel labelDuration;
private JButton buttonOpen;
private JButton buttonPlay;
private JButton buttonPause;
private JButton buttonRewind;
private JButton buttonForward;
private JSlider sliderTime;
private Dimension buttonDimension = new Dimension(BUTTON_WIDTH,BUTTON_HEIGTH);
public PlayerView()
{
setLayout(new BorderLayout());
labelFileName = new JLabel("File Loaded:");
labelTimeCounter = new JLabel("00:00:00.000");
labelDuration = new JLabel("00:00:00.000");
sliderTime = new JSlider(0, 1000, 0);;
sliderTime.setValue(0);
sliderTime.setEnabled(false);
buttonOpen = new JButton("Open");
buttonOpen.setPreferredSize(buttonDimension);
buttonOpen.addActionListener(this);
buttonPlay = new JButton("Play");
buttonPlay.setEnabled(false);
buttonPlay.setPreferredSize(buttonDimension);
buttonPlay.addActionListener(this);
buttonPause = new JButton("Pause");
buttonPause.setEnabled(false);
buttonPause.setPreferredSize(buttonDimension);
buttonPause.addActionListener(this);
buttonRewind = new JButton("Rewind");
buttonRewind.setEnabled(false);
buttonRewind.setPreferredSize(buttonDimension);
buttonRewind.addActionListener(this);
buttonForward= new JButton("Forward");
buttonForward.setEnabled(false);
buttonForward.setPreferredSize(buttonDimension);
buttonForward.addActionListener(this);
init();
}
public void enableButtonPlay()
{
buttonPlay.setEnabled(true);
}
#Override
public void actionPerformed(ActionEvent event)
{
Object source = event.getSource();
if (source instanceof JButton)
{
JButton button = (JButton) source;
if (button == buttonOpen)
{
openFile();
}
else if (button == buttonPlay)
{
if (!isPlaying)
{
playBack();
}
else
{
stopPlaying();
}
}
else if (button == buttonPause)
{
if (!isPause)
{
pausePlaying();
}
else
{
resumePlaying();
}
}
else if (button == buttonRewind)
{
if (!isPause)
{
rewind();
}
}
else if (button == buttonForward)
{
if (!isPause)
{
forward();
}
}
}
}
public void openFile(String path)
{
audioFilePath = path ;
if (isPlaying || isPause)
{
stopPlaying();
while (player.getAudioClip().isRunning())
{
try
{
Thread.sleep(100);
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
}
}
playBack();
}
private void openFile()
{
JFileChooser fileChooser = null;
if (lastOpenPath != null && !lastOpenPath.equals(""))
{
fileChooser = new JFileChooser(lastOpenPath);
}
else
{
fileChooser = new JFileChooser();
}
FileFilter wavFilter = new FileFilter()
{
#Override
public String getDescription()
{
return "Sound file (*.WAV)";
}
#Override
public boolean accept(File file)
{
if (file.isDirectory())
{
return true;
}
else
{
return file.getName().toLowerCase().endsWith(".wav");
}
}
};
fileChooser.setFileFilter(wavFilter);
fileChooser.setDialogTitle("Open Audio File");
fileChooser.setAcceptAllFileFilterUsed(false);
int userChoice = fileChooser.showOpenDialog(this);
if (userChoice == JFileChooser.APPROVE_OPTION)
{
audioFilePath = fileChooser.getSelectedFile().getAbsolutePath();
lastOpenPath = fileChooser.getSelectedFile().getParent();
if (isPlaying || isPause)
{
stopPlaying();
while (player.getAudioClip().isRunning())
{
try
{
Thread.sleep(100);
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
}
}
playBack();
}
}
private void playBack()
{
timer = new PlayingTimer(labelTimeCounter, sliderTime);
timer.start();
isPlaying = true;
playbackThread = new Thread(new Runnable()
{
#Override
public void run()
{
try
{
buttonPlay.setText("Stop");
buttonPlay.setEnabled(true);
buttonRewind.setEnabled(true);
buttonForward.setEnabled(true);
buttonPause.setText("Pause");
buttonPause.setEnabled(true);
player.load(audioFilePath);
timer.setAudioClip(player.getAudioClip());
labelFileName.setText("Playing File: " + ((File)new File(audioFilePath)).getName());
sliderTime.setMinimum(0);
sliderTime.setMaximum((int)player.getClipMicroSecondLength());
labelDuration.setText(player.getClipLengthString());
player.play();
labelFileName.setText("File Loaded: " + ((File)new File(audioFilePath)).getName());
resetControls();
}
catch (UnsupportedAudioFileException ex)
{
JOptionPane.showMessageDialog(
PlayerView.this,
"The audio format is unsupported!",
"Error",
JOptionPane.ERROR_MESSAGE);
resetControls();
}
catch (LineUnavailableException ex)
{
JOptionPane.showMessageDialog(
PlayerView.this,
"Could not play the audio file because line is unavailable!",
"Error",
JOptionPane.ERROR_MESSAGE);
resetControls();
}
catch (IOException ex)
{
JOptionPane.showMessageDialog(
PlayerView.this,
"I/O error while playing the audio file!",
"Error",
JOptionPane.ERROR_MESSAGE);
resetControls();
}
}
});
playbackThread.start();
}
private void stopPlaying()
{
isPause = false;
buttonPause.setText(" Pause ");
buttonPause.setEnabled(false);
buttonRewind.setEnabled(false);
buttonForward.setEnabled(false);
timer.reset();
timer.interrupt();
player.stop();
playbackThread.interrupt();
}
private void pausePlaying()
{
labelFileName.setText("File Loaded: " + ((File)new File(audioFilePath)).getName());
buttonRewind.setEnabled(false);
buttonForward.setEnabled(false);
buttonPause.setText("Resume");
isPause = true;
player.pause();
timer.pauseTimer();
playbackThread.interrupt();
}
private void resumePlaying()
{
labelFileName.setText("Playing File: " + ((File)new File(audioFilePath)).getName());
buttonPause.setText(" Pause ");
buttonRewind.setEnabled(true);
buttonForward.setEnabled(true);
isPause = false;
player.resume();
timer.resumeTimer();
playbackThread.interrupt();
}
private void rewind()
{
player.rewind();
timer.rewind();
timer.interrupt();
playbackThread.interrupt();
}
private void forward()
{
player.forward();
timer.forward();
timer.interrupt();
playbackThread.interrupt();
}
private void resetControls()
{
timer.reset();
timer.interrupt();
isPlaying = false;
buttonPlay.setText("Play");
buttonPause.setEnabled(false);
buttonRewind.setEnabled(false);
buttonForward.setEnabled(false);
}
private void init()
{
add(labelFileName, BorderLayout.NORTH);
add(labelTimeCounter, BorderLayout.WEST);
add(labelDuration, BorderLayout.EAST);
add(sliderTime, BorderLayout.CENTER);
JPanel buttonContainer =new JPanel();
add(buttonContainer, BorderLayout.SOUTH);
buttonContainer.add(buttonOpen);
buttonContainer.add(buttonPlay);
buttonContainer.add(buttonPause);
buttonContainer.add(buttonRewind);
buttonContainer.add(buttonForward);
}
}
Okay, so, the issue with Clip. Here is an MCVE that, from the way you've described the problem, may reproduce it:
class TestFramePosition {
public static void main(String[] a) throws Exception {
File file = new File(a.length > 0 ? a[0] : "path/to/file.extension");
AudioInputStream ais = AudioSystem.getAudioInputStream(file);
final Clip clip = AudioSystem.getClip();
clip.open(ais);
clip.start();
new Thread(new Runnable() {
#Override
public void run() {
while(clip.isRunning()) {
try {
System.out.println(clip.getMicrosecondPosition());
Thread.sleep(1000 / 10);
} catch(InterruptedException ignored) {}
}
}
}).start();
System.in.read();
System.exit(0);
}
}
I was unable to reproduce it on OSX 10.6.8 and Windows XP, but you may run that code to see if it does on your particular platform.
So, the issue here is that, as I said in comments, since sound playback is dependent on platform-specific stuff, classes like Clip will have varied implementations. These will behave slightly differently.
For example, I found that when a Clip is done playing, the Clip on my Mac computer (a com.sun.media.sound.MixerClip) returns 0 for the position, while the Clip on my Windows computer (a com.sun.media.sound.DirectAudioDevice$DirectClip) returns the maximum value for the position. Just another small example of implementations being programmed differently.
The issue is that the contract for these methods is defined a little vaguely but, specifically, it is defined by 'the number of sample frames captured by, or rendered from, the line since it was opened'. This means it may not accurately represent the playback position, rather it is the amount of data read and written.
I did spend awhile yesterday perusing JDK source code but I was unable to find anything that would point towards the behavior you are seeing.
Anyway, what it comes down to is whether you are OK with slightly anomalous behavioral differences from platform to platform. What you are seeing may be a bug and if the above MCVE reproduces it, you may report it; however I would not personally expect it to get fixed in any timely manner because this is a section of the JDK that does not get a lot of attention. Also it is gradually being superseded by JavaFX.
Some other things:
You are sharing state between threads without synchronization. This leads to memory errors. You should read the concurrency tutorials, specifically synchronization.
You should always cap frame rate when working with Swing. Swing will not paint at 1000FPS, it will merge repaints aggressively. Updating the slider at this rate was just flooding the EDT.
You may use SourceDataLine because it gives you much greater control over the buffering behavior. The downside is that you have to basically reimplement the functionality of Clip.
Here is an MCVE demonstrating a playback loop to power a JSlider.
This example doesn't demonstrate seeking. Also since, AudioInputStream does not generally support mark operations, seeking backwards is a bit of a hassle. A backwards seek process is:
Stop the current playback and discard it.
Create a new AudioInputStream and seek forwards.
Start the new playback.
Also, if you are planning to use the JSlider to seek, you will probably run in to an issue where calling setValue on a JSlider will cause it to fire a ChangeEvent. So you can't update the slider's value programmatically and also listen to it without rejiggering it. This is really a Q&A itself so if you experience this problem I recommend you ask a new question.
import javax.sound.sampled.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.Dimension;
import java.awt.BorderLayout;
import java.io.File;
import java.io.IOException;
public class PlaybackSlider implements Runnable, ActionListener {
public static void main(String[] args) {
SwingUtilities.invokeLater(new PlaybackSlider());
}
JButton open;
JButton play;
JSlider slider;
JLabel label;
File file;
PlaybackLoop player;
#Override
public void run() {
JFrame frame = new JFrame("Playback Slider");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel content = new JPanel(new BorderLayout()) {
#Override
public Dimension getPreferredSize() {
Dimension pref = super.getPreferredSize();
pref.width = 480;
return pref;
}
};
slider = new JSlider(JSlider.HORIZONTAL, 0, 1000, 0);
content.add(slider, BorderLayout.CENTER);
JToolBar bar = new JToolBar(JToolBar.HORIZONTAL);
bar.setFloatable(false);
content.add(bar, BorderLayout.SOUTH);
open = new JButton("Open");
play = new JButton("Play");
open.addActionListener(this);
play.addActionListener(this);
label = new JLabel("");
bar.add(open);
bar.add(new JLabel(" "));
bar.add(play);
bar.add(new JLabel(" "));
bar.add(label);
frame.setContentPane(content);
frame.pack();
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent ae) {
Object source = ae.getSource();
if(source == open) {
File f = getFile();
if(f != null) {
file = f;
label.setText(file.getName());
stop();
}
}
if(source == play) {
if(file != null) {
if(player != null) {
stop();
} else {
start();
}
}
}
}
File getFile() {
JFileChooser diag = new JFileChooser();
int choice = diag.showOpenDialog(null);
if(choice == JFileChooser.APPROVE_OPTION) {
return diag.getSelectedFile();
} else {
return null;
}
}
void start() {
try {
player = new PlaybackLoop(file);
new Thread(player).start();
play.setText("Stop");
} catch(Exception e) {
player = null;
showError("the file couldn't be played", e);
}
}
void stop() {
if(player != null) {
player.stop();
}
}
void showError(String msg, Throwable cause) {
JOptionPane.showMessageDialog(null,
"There was an error because " + msg +
(cause == null ? "." : "\n(" + cause + ").")
);
}
class PlaybackLoop implements Runnable {
AudioInputStream in;
SourceDataLine line;
AudioFormat fmt;
int bufferSize;
boolean stopped;
PlaybackLoop(File file) throws Exception {
try {
in = AudioSystem.getAudioInputStream(file);
fmt = in.getFormat();
bufferSize = (int)(fmt.getFrameSize() * (fmt.getSampleRate() / 15));
line = AudioSystem.getSourceDataLine(fmt);
line.open(fmt, bufferSize);
} catch(Exception e) {
if(in != null)
in.close();
if(line != null)
line.close();
throw e;
}
}
void stop() {
synchronized(this) {
this.stopped = true;
}
}
#Override
public void run() {
line.start();
byte[] buf = new byte[bufferSize];
try {
try {
int b;
long elapsed = 0;
long total = in.getFrameLength();
for(;;) {
synchronized(this) {
if(stopped) {
break;
}
}
b = in.read(buf, 0, buf.length);
if(b < 0) {
break;
}
elapsed += b / fmt.getFrameSize();
updateSlider(elapsed, total);
line.write(buf, 0, b);
}
} finally {
line.close();
in.close();
}
} catch(IOException e) {
e.printStackTrace(System.err);
showError("there was a problem during playback", e);
}
endOnEDT();
}
void updateSlider(double elapsed, double total) {
final double amt = elapsed / total;
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
slider.setValue((int)Math.round(slider.getMaximum() * amt));
}
});
}
void endOnEDT() {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
player = null;
slider.setValue(0);
play.setText("Play");
}
});
}
}
}
I assume you are wanting to use the JSlider as a progress bar and that at the moment you are setting the max value, the current position is at the end of the audioClip. (Are you dealing with Clip or AudioClip? AudioClip doesn't have a way to read its position AFAIK.) If you are using Clip, it would be safer to set the max with audioClip.getMicrosecondLength().
Since the audio has to play on a different thread than the one where the JSlider is being updated, I'd recommend making your audioClip a volatile variable. That might help with cross-thread weirdness that sometimes occurs.
Thread.sleep(1) at best can only update every millisecond. On some systems (older Windows) the method's reliance on the system clock means the actual updates are as slow as 16 millis apart. But updating the JSlider at more than 60 fps is probably moot. Screen monitors often are set to 60Hz, and there's only so much the human eye can take in.
Also there is only so much the ear can discern in terms of timing. For example, it is hard to tell if two percussive events happen at the same time if there is less than a couple milliseconds difference.
There are several issues with your code.
As Phil Freihofner pointed out, the sleep(1) and the treatment of the isRunning and isPause fields look highly dubious. To some extent, this is unrelated to your actual question, but worth noting here, because it may also cause problems later.
Regardless of that, the approach that Zoran Regvart showed is basically the way to go. The code in the given form may have suffered from some rounding issues. However, the general idea for cases like this is always the same:
You have a source interval [minA...maxA]
You have a target interval [minB...maxB]
You want a mapping between the two
In this case, it's a good practice to normalize the intervals. That is, to map the value from the source interval to a value between 0.0 and 1.0, and then map this normalized value to the target interval.
In the most generic form, this can be written as
long minA = ...
long maxA = ...
long a = ... // The current value in the source interval
int minB = ...
int maxB = ...
int b; // The value to compute in the target interval
// Map the first value to a value between 0.0 and 1.0
double normalized = (double)(a - minA)/(maxA-minA);
b = (int)(minB + normalized * (maxB - minB));
Fortunately, your "min" values are all zero here, so it's a bit simpler. Here is a MCVE (with some dummy classes). The most relevant part is the updateSlider method at the bottom.
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JSlider;
import javax.swing.SwingUtilities;
public class SliderMappingTest
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
createAndShowGUI();
}
});
}
private static void createAndShowGUI()
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JButton startButton = new JButton("Start");
final JSlider progressSlider = new JSlider(0, 1000, 0);
startButton.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
startButton.setEnabled(false);
SliderMappingDummyAudioClip audioClip =
new SliderMappingDummyAudioClip();
SliderMappingDummyPlayer player =
new SliderMappingDummyPlayer(progressSlider, audioClip);
player.start();
}
});
f.getContentPane().setLayout(new GridLayout());
f.getContentPane().add(startButton);
f.getContentPane().add(progressSlider);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
class SliderMappingDummyAudioClip
{
private long startMicros;
void start()
{
startMicros = System.nanoTime() / 1000L;
}
long getMicrosecondLength()
{
// 10 seconds
return 10L * 1000L * 1000L;
}
long getMicrosecondPosition()
{
return (System.nanoTime() / 1000L) - startMicros;
}
public boolean isRunning()
{
return getMicrosecondPosition() <= getMicrosecondLength();
}
}
class SliderMappingDummyPlayer
{
private final SliderMappingDummyAudioClip audioClip;
private final JSlider slider;
SliderMappingDummyPlayer(
JSlider slider,
SliderMappingDummyAudioClip audioClip)
{
this.slider = slider;
this.audioClip = audioClip;
}
void start()
{
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
doRun();
}
});
t.setDaemon(true);
t.start();
}
private void doRun()
{
audioClip.start();
while (audioClip.isRunning())
{
updateSlider();
try
{
Thread.sleep(30);
}
catch (InterruptedException ex)
{
Thread.currentThread().interrupt();
return;
}
}
}
private void updateSlider()
{
long currentMicros = audioClip.getMicrosecondPosition();
// Compute the progress as a value between 0.0 and 1.0
double progress =
(double)currentMicros / audioClip.getMicrosecondLength();
// Compute the slider value to indicate the progress
final int sliderValue = (int)(progress * slider.getMaximum());
System.out.println("update "+progress);
// Update the slider with the new value, on the Event Dispatch Thread
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
slider.setValue(sliderValue);
}
});
}
}
Are you sure you want to set the maximum to current position?
How about mapping longs to ints by division:
long coefficient = clip.getMicrosecondLength() / Integer.MAX_VALUE;
slider.setMinimum(0);
slider.setMaximum((int) (clip.getMicrosecondLength() / coefficient));
...
slider.setValue((int) (clip.getMicrosecondPosition() / coefficient));

Progressbar: how to create deep copy of original object

I'm trying to use a progress bar similar to this one below in Java:
public class MyProgressSplashScreen extends JWindow
{
private final JProgressBar progressbar;
private final ExecutorService autoProgressExecutor = Executors.newFixedThreadPool(1);
public MyProgressSplashScreen(final int theMin, final int theMax)
{
super();
final JPanel contentPanel = new JPanel(new BorderLayout());
contentPanel.setBorder(BorderFactory.createBevelBorder(BevelBorder.RAISED));
if (theMin != -1 && theMax != -1)
{
progressbar = new JProgressBar(SwingConstants.HORIZONTAL, theMin, theMax);
}
else
{
progressbar = new JProgressBar(SwingConstants.HORIZONTAL);
progressbar.setIndeterminate(true);
}
progressbar.setStringPainted(true);
contentPanel.add(progressbar, BorderLayout.SOUTH);
add(contentPanel);
pack();
setAlwaysOnTop(true);
}
public void showProgress(final int theValueTo, final int theEstimatedTimeInSeconds)
{
showProgress(progressbar.getValue(), theValueTo, theEstimatedTimeInSeconds);
}
public void showProgress(final int theValueFrom, final int theValueTo,
final int theEstimatedTimeInSeconds)
{
setVisible(true);
autoProgressExecutor.execute(new Runnable()
{
#Override
public void run()
{
int numberOfSteps = theValueTo - theValueFrom;
long timeToWait = TimeUnit.SECONDS.toMillis(theEstimatedTimeInSeconds)
/ numberOfSteps;
for (int i = theValueFrom; i <= theValueTo; i++)
{
progressbar.setValue(i);
try
{
TimeUnit.MILLISECONDS.sleep(timeToWait);
}
catch (final InterruptedException e) { }
}
if (progressbar.getValue() == 100) { setVisible(false); }
}
});
}
}
I am however not able to pass a copy of the MyProgressSplashScreen in order to let a separate thread update the progress.
For instance the program below starts counting from 0 to 10 and then restarts from 0 to 30 while it shouldn't reset to zero!
public class TestSplashScreen
{
private final MyProgressSplashScreen myProgressSplashScreen = new MyProgressSplashScreen(-1,-1);
public static void main(String args[])
{
TestSplashScreen testInvoke = new TestSplashScreen();
testInvoke.synchronize();
}
public void synchronize()
{
Runnable runnable = new Runnable()
{
#Override
public void run()
{
myProgressSplashScreen.showProgress(10, 2);
myProgressSplashScreen.toFront();
MyRunnable myRunnable = new MyRunnable();
myRunnable.setSyncProgressSplashScreen(myProgressSplashScreen);
Thread t1 = new Thread(myRunnable);
t1.start();
}
};
runnable.run();
}
}
class MyRunnable implements Runnable
{
MyProgressSplashScreen syncProgressSplashScreen;
public void setSyncProgressSplashScreen(MyProgressSplashScreen syncProgressSplashScreen)
{
this.syncProgressSplashScreen = syncProgressSplashScreen;
}
#Override
public void run()
{
syncProgressSplashScreen.showProgress(30, 3);
}
}
The problem is you call syncProgressSplashScreen.showProgress 2 times. The first time it blocks the thread causing it to increment from 0 to 10 then you call it again going from 0 to 30. Remove the line that reads myProgressSplashScreen.showProgress(10, 2); and it wont do it 2 times. Also I noticed you dont set your maximum value for the progress bar so unless you call myProgressSplashScreen.showProgress(100, 2) it wont go to 100%.

how can i solve this error

This is the complete code :
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.Thread;
class jProgressBar {
JProgressBar pb;
JButton start;
int i;
jProgressBar() {
buildGUI();
hookUpEvents();
}
public void buildGUI() {
JFrame fr=new JFrame("Progress Bar");
JPanel p=new JPanel();
p.setLayout(new FlowLayout(FlowLayout.CENTER));
JPanel barPanel=new JPanel();
barPanel.setLayout(new GridLayout(2,0,50,50));
pb=new JProgressBar(0,10);
start=new JButton("Start Demo");
fr.add(p);
barPanel.add(start);
barPanel.add(pb);
p.add(barPanel);
fr.setSize(500,500);
fr.setVisible(true);
}
public void hookUpEvents() {
start.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
Runnable r=new Runnable() {
public void run() {
action(ae); // LINE 39
}
};
Thread th=new Thread(r);
th.start();
} catch(Exception exc) {
System.out.println(exc);
}
}
});
}
public void action(ActionEvent ae) {
start.setVisible(false);
try {
Runnable rp=new Runnable() {
public void run() {
i++;
pb.setValue(i);
try {
Thread.sleep(2000);
} catch(Exception exc) {
System.out.println(exc);
}
if(i==5) {
pb.setString("Half Done!");
}
else if(i==10) {
pb.setString("Completed!");
}
}
};
Thread th=new Thread(rp);
th.start();
} catch(Exception exc) {
System.out.println(exc);
}
}
public static void main(String args[]) {
new jProgressBar();
}
}
This is the error produced on cmd:
d:\UnderTest>javac jProgressBar.java
jProgressBar.java:39: local variable ae is accessed from within inner class; needs to be declared fina
l
action(ae);
^
1 error
What is this error and how can I solve this error?
Declare the variable ae as final:
public void actionPerformed(final ActionEvent ae) {
This means that it cannot be assigned a new value, which should be fine according to your current code.
a very nice example for SwingWorker
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
public class SwingWorkerExample extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private final JButton startButton, stopButton;
private JScrollPane scrollPane = new JScrollPane();
private JList listBox = null;
private DefaultListModel listModel = new DefaultListModel();
private final JProgressBar progressBar;
private mySwingWorker swingWorker;
public SwingWorkerExample() {
super("SwingWorkerExample");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new GridLayout(2, 2));
startButton = makeButton("Start");
stopButton = makeButton("Stop");
stopButton.setEnabled(false);
progressBar = makeProgressBar(0, 99);
listBox = new JList(listModel);
scrollPane.setViewportView(listBox);
getContentPane().add(scrollPane);
//Display the window.
pack();
setVisible(true);
}
//Class SwingWorker<T,V> T - the result type returned by this SwingWorker's doInBackground
//and get methods V - the type used for carrying out intermediate results by this SwingWorker's
//publish and process methods
private class mySwingWorker extends javax.swing.SwingWorker<ArrayList<Integer>, Integer> {
//The first template argument, in this case, ArrayList<Integer>, is what s returned by doInBackground(),
//and by get(). The second template argument, in this case, Integer, is what is published with the
//publish method. It is also the data type which is stored by the java.util.List that is the parameter
//for the process method, which recieves the information published by the publish method.
#Override
protected ArrayList<Integer> doInBackground() {
//Returns items of the type given as the first template argument to the SwingWorker class.
if (javax.swing.SwingUtilities.isEventDispatchThread()) {
System.out.println("javax.swing.SwingUtilities.isEventDispatchThread() returned true.");
}
Integer tmpValue = new Integer(1);
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 100; j++) { //find every 100th prime, just to make it slower
tmpValue = FindNextPrime(tmpValue.intValue());
//isCancelled() returns true if the cancel() method is invoked on this class. That is the proper way
//to stop this thread. See the actionPerformed method.
if (isCancelled()) {
System.out.println("SwingWorker - isCancelled");
return list;
}
}
//Successive calls to publish are coalesced into a java.util.List, which is what is received by process,
//which in this case, isused to update the JProgressBar. Thus, the values passed to publish range from
//1 to 100.
publish(new Integer(i));
list.add(tmpValue);
}
return list;
}//Note, always use java.util.List here, or it will use the wrong list.
#Override
protected void process(java.util.List<Integer> progressList) {
//This method is processing a java.util.List of items given as successive arguments to the publish method.
//Note that these calls are coalesced into a java.util.List. This list holds items of the type given as the
//second template parameter type to SwingWorker. Note that the get method below has nothing to do with the
//SwingWorker get method; it is the List's get method. This would be a good place to update a progress bar.
if (!javax.swing.SwingUtilities.isEventDispatchThread()) {
System.out.println("javax.swing.SwingUtilities.isEventDispatchThread() + returned false.");
}
Integer percentComplete = progressList.get(progressList.size() - 1);
progressBar.setValue(percentComplete.intValue());
}
#Override
protected void done() {
System.out.println("doInBackground is complete");
if (!javax.swing.SwingUtilities.isEventDispatchThread()) {
System.out.println("javax.swing.SwingUtilities.isEventDispatchThread() + returned false.");
}
try {
//Here, the SwingWorker's get method returns an item of the same type as specified as the first type parameter
//given to the SwingWorker class.
ArrayList<Integer> results = get();
for (Integer i : results) {
listModel.addElement(i.toString());
}
} catch (Exception e) {
System.out.println("Caught an exception: " + e);
}
startButton();
}
boolean IsPrime(int num) { //Checks whether a number is prime
int i;
for (i = 2; i <= num / 2; i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
protected Integer FindNextPrime(int num) { //Returns next prime number from passed arg.
do {
if (num % 2 == 0) {
num++;
} else {
num += 2;
}
} while (!IsPrime(num));
return new Integer(num);
}
}
private JButton makeButton(String caption) {
JButton b = new JButton(caption);
b.setActionCommand(caption);
b.addActionListener(this);
getContentPane().add(b);
return b;
}
private JProgressBar makeProgressBar(int min, int max) {
JProgressBar progressBar1 = new JProgressBar();
progressBar1.setMinimum(min);
progressBar1.setMaximum(max);
progressBar1.setStringPainted(true);
progressBar1.setBorderPainted(true);
getContentPane().add(progressBar1);
return progressBar1;
}
private void startButton() {
startButton.setEnabled(true);
stopButton.setEnabled(false);
System.out.println("SwingWorker - Done");
}
#Override
public void actionPerformed(ActionEvent e) {
if ("Start" == null ? e.getActionCommand() == null : "Start".equals(e.getActionCommand())) {
startButton.setEnabled(false);
stopButton.setEnabled(true);
// Note that it creates a new instance of the SwingWorker-derived class. Never reuse an old one.
(swingWorker = new mySwingWorker()).execute(); // new instance
} else if ("Stop" == null ? e.getActionCommand() == null : "Stop".equals(e.getActionCommand())) {
startButton.setEnabled(true);
stopButton.setEnabled(false);
swingWorker.cancel(true); // causes isCancelled to return true in doInBackground
swingWorker = null;
}
}
public static void main(String[] args) {
// Notice that it kicks it off on the event-dispatching thread, not the main thread.
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
SwingWorkerExample swingWorkerExample = new SwingWorkerExample();
}
});
}
}
There are some counterproductive issues present.
Swing is single-thread based, and all actions must be done on the EDT. For that reason, your JProgressBar doesn't update correctly. See also Concurrency in Swing.
Don't use Thread.sleep(int) in Swing, and certainly not in an action listener.
By using Runnable, it is possible to update JProgressBar; but as mentioned, the method must be run from invokeLater().
For that, SwingWorker would be better, as shown below and here.
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import javax.swing.*;
public class TestProgressBar {
private static void createAndShowUI() {
JFrame frame = new JFrame("TestProgressBar");
frame.getContentPane().add(new TestPBGui().getMainPanel());
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() {
#Override
public void run() {
createAndShowUI();
}
});
}
private TestProgressBar() {
}
}
class TestPBGui {
private JPanel mainPanel = new JPanel();
public TestPBGui() {
JButton yourAttempt = new JButton("Your attempt to show Progress Bar");
JButton myAttempt = new JButton("My attempt to show Progress Bar");
yourAttempt.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
yourAttemptActionPerformed();
}
});
myAttempt.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
myAttemptActionPerformed();
}
});
mainPanel.add(yourAttempt);
mainPanel.add(myAttempt);
}
private void yourAttemptActionPerformed() {
Window thisWin = SwingUtilities.getWindowAncestor(mainPanel);
JDialog progressDialog = new JDialog(thisWin, "Uploading...");
JPanel contentPane = new JPanel();
contentPane.setPreferredSize(new Dimension(300, 100));
JProgressBar bar = new JProgressBar(0, 100);
bar.setIndeterminate(true);
contentPane.add(bar);
progressDialog.setContentPane(contentPane);
progressDialog.pack();
progressDialog.setLocationRelativeTo(null);
Task task = new Task("Your attempt");
task.execute();
progressDialog.setVisible(true);
while (!task.isDone()) {
}
progressDialog.dispose();
}
private void myAttemptActionPerformed() {
Window thisWin = SwingUtilities.getWindowAncestor(mainPanel);
final JDialog progressDialog = new JDialog(thisWin, "Uploading...");
JPanel contentPane = new JPanel();
contentPane.setPreferredSize(new Dimension(300, 100));
final JProgressBar bar = new JProgressBar(0, 100);
bar.setIndeterminate(true);
contentPane.add(bar);
progressDialog.setContentPane(contentPane);
progressDialog.pack();
progressDialog.setLocationRelativeTo(null);
final Task task = new Task("My attempt");
task.addPropertyChangeListener(new PropertyChangeListener() {
#Override
public void propertyChange(PropertyChangeEvent evt) {
if (evt.getPropertyName().equalsIgnoreCase("progress")) {
int progress = task.getProgress();
if (progress == 0) {
bar.setIndeterminate(true);
} else {
bar.setIndeterminate(false);
bar.setValue(progress);
progressDialog.dispose();
}
}
}
});
task.execute();
progressDialog.setVisible(true);
}
public JPanel getMainPanel() {
return mainPanel;
}
}
class Task extends SwingWorker<Void, Void> {
private static final long SLEEP_TIME = 4000;
private String text;
public Task(String text) {
this.text = text;
}
#Override
public Void doInBackground() {
setProgress(0);
try {
Thread.sleep(SLEEP_TIME);// imitate a long-running task
} catch (InterruptedException e) {
}
setProgress(100);
return null;
}
#Override
public void done() {
System.out.println(text + " is done");
Toolkit.getDefaultToolkit().beep();
}
}

Categories