Skip to content

Instantly share code, notes, and snippets.

Created October 26, 2015 19:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save anonymous/e835dd43a6effccec79f to your computer and use it in GitHub Desktop.
Save anonymous/e835dd43a6effccec79f to your computer and use it in GitHub Desktop.
Demonstrate concurrency using timer.
package supercat1;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*; // Using Swing components and containers
import java.util.Timer
// A Swing application extends javax.swing.JFrame
public class supercat1 extends JFrame {
private JTextField tfCount;
// Use Swing's JTextField instead of AWT's TextField
private int count = 0;
//The TimerTask code is executed every second and the tfCount text field is updated depending on the value of mState.
//declare different states of the updater
private final int GOING_UP = 1;
private final int GOING_DOWN = 2;
private final int STOP = 3;
private int mState = STOP; //default state is stop
private Timer mTimer = new Timer();
private TimerTask mTask = new TimerTask() {
@Override
public void run() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
//should use a switch statement
if (mState == GOING_UP){
++count;
}else if(mState == GOING_DOWN){
--count;
}
tfCount.setText("" + count);
}
});
}
}
public supercat1 () {
// Get the content pane of top-level container Jframe
// Components are added onto content pane
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
cp.add(new JLabel("Counter"wink);
tfCount = new JTextField(count + "", 10);
tfCount.setEditable(false);
tfCount.setHorizontalAlignment(JTextField.RIGHT);
cp.add(tfCount);
JButton btnCount = new JButton("Count Up" ) ;
cp.add(btnCount);
JButton btnCountd = new JButton("Count Down" ) ;
cp.add(btnCountd);
JButton btnCounts = new JButton("Stop" ) ;
cp.add(btnCounts);
btnCount.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
mState = GOING_UP;
if (mState == STOP){//if it was previously stopped, start it
mTimer.schedule(mTask, 1000, 1000)//execute mTask every second
}
}
});
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Exit program if Jframe's close-window button clicked
setSize(300, 100);
setTitle("Supercat Counter" );
setVisible(true); // show it
}
public static void main(String[] args) {
// Recommended to run the GUI construction in
// Event Dispatching thread for thread-safet operations
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new supercat1(); // Let the constructor does the job
}
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment