I am trying to create a simple GUI form which has only 2 elements – a simple label and a button. The text displayed on button is ‘Start’. The label is displaying 0 by default.
When I click Start button following actions shall take place:
- Counter shall start incrementing by 1 from 0 at every 1 second.
- Text displayed on the Start button shall change to Stop.
- When again I click on the same button (now showing caption as Stop), increment shall stop.
- Text on the button shall change to Start. And so on…
I am developing my application in Netbeans.
As shown in the above diagram, there are 2 .java files
Contents of AGC.java are:
public class AGC extends javax.swing.JFrame
{
public AGC()
{
initComponents();
}
public static void main(String args[])
{
java.awt.EventQueue.invokeLater(new Runnable() {
public void run()
{
new AGC().setVisible(true);
}
});
}
private javax.swing.JButton btnStartStop; // name of start stop button
private javax.swing.JLabel lblCounter; // name of the label
}
Contents of Main.java are:
public class Main
{
public static int count = 0;
public static boolean started = false;
}
I want to implement following logic:
private void btnStartStopMouseClicked(java.awt.event.MouseEvent evt)
{
if (Main.stared == true)
{
// logic to start counting
}
else
{
// logic to stop counting
}
}
My problem is this:
- How to update lblCounter at every 1 second?
- What logic shall I implement to start the timer of 1 second and how to access lblCounter in that method ?
Kindly help. A working code would be very highly appreciated. Thanks in advance.
Jay
Simply use a javax.swing.Timer, and make one ActionListener, to do this thing for you . Give me ten mins for a working code example 🙂
Here is a sample program for further help :
If you want the counter to again revert back to 0, on Stopping the Timer, simply add
this part to the
buttonAction‘sactionPerformed(...)method.