My DigitalClock not working - java

I made a digital clock. but its not working properly.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Date;
public class DigitalClock extends JFrame implements ActionListener {
JLabel l1 = new JLabel();
Timer t;
public DigitalClock() {
super("Digital Clock");
l1.setFont( new Font("Verdana",Font.BOLD,11) );
l1.setHorizontalAlignment( JLabel.RIGHT);
l1.setVerticalAlignment( JLabel.BOTTOM);
t = new Timer(1000,this);
getContentPane().add(l1);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(110,100);
setVisible(true);
// call actionPerformed to get Time at the startup
actionPerformed(null);
}
public void actionPerformed(ActionEvent evt) {
l1.setText( new Date().toString().substring(11,19));
}
public static void main(String args[]) {
new DigitalClock();
}
} // end of class
I made a digital clock. but its not working properly.
Help me i can't find the problem..
plz help..
output is constant time

After creating Time obj just start timer
t.start();

in output time is constant not move. but i want continues time clock
Did you start the Timer?
If you start the Timer then you don't even need:
// actionPerformed(null);

Related

Java timer issue with starting application

very new to java so please explain at a basic level. Attempting to make a snake game. In the process of typing up the code for the games background. Having an issue with the timer. The lines with issues marked with ***
package snake;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
public class Snake implements ActionListener {
public JFrame jframe;
public RenderPanel renderPanel;
public static Snake snake;
public Snake() {
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
jframe = new JFrame("Snake");
jframe.setVisible(true);
jframe.setSize(800, 700);
jframe.setLocation(dim.width / 2 - jframe.getWidth() / 2, dim.height / 2 - jframe.getHeight() / 2);
jframe.add(renderPanel = new RenderPanel());
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main (String []args) {
snake = new Snake();
}
#Override
public void actionPerformed(ActionEvent arg0) {
renderPanel.repaint();
}
You cannot initialize a Timer with a int and a Snake object. That is not supported by the Timer class. Have a look at the Java Api. The Constructor Summary Shows you, which Constructors exist for the Timer class.
When you want to do something after a defined time do the following:
Timer timer = new Timer();
timer.schedule(new ReceiverTask(), 1000);
The 1000 is the delay in milliseconds untill the run method of the ReceiverTask will be called.
ReceiverTask should be a class extending TimeTask. For example:
class ReceiverTask extends TimerTask {
public void run() {
//update your Background her
}
}

Update a Label with a Swing Timer

I'm having some trouble with this piece of code.
I'm starting a timer with a random number, and I want to update a JLabel with the countdown, every second. But I haven't figured out how to do so, since the only listener the timer triggers is at the end of it (that I know).
here's the code:
int i = getTimer(maxWait);
te1 = new Timer(i, this);
label.setText(i+"");
te1.start();
...
public int getTimer(int max){
Random generator = new Random();
int i = generator.nextInt(max);
return i*1000;
}
...
public void actionPerformed(ActionEvent ev){
if(ev.getSource() == te1){
label.setText(i+"");
te1.stop();
}
}
I don't really understand your question why you are using the Random, but here are some observations:
I want to update a JLabel with the countdown, every second.
Then you need to set the Timer to fire every second. So the parameter to the Timer is 1000, not some random number.
Also, in your actionPerformed() method you stop the Timer the first time it fires. If you are doing a count down of some kind then you would only stop the Timer when the time reaches 0.
Here is a simple example of using a Timer. It just updates the time every second:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
public class TimerTime extends JPanel implements ActionListener
{
private JLabel timeLabel;
public TimerTime()
{
timeLabel = new JLabel( new Date().toString() );
add( timeLabel );
Timer timer = new Timer(1000, this);
timer.setInitialDelay(1);
timer.start();
}
#Override
public void actionPerformed(ActionEvent e)
{
//System.out.println(e.getSource());
timeLabel.setText( new Date().toString() );
}
private static void createAndShowUI()
{
JFrame frame = new JFrame("TimerTime");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add( new TimerTime() );
frame.setLocationByPlatform( true );
frame.pack();
frame.setVisible( true );
}
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
createAndShowUI();
}
});
}
}
If you need more help then update your question with a proper SSCCE demonstrating the problem. All questions should have a proper SSCCE, not just a few random lines of code so we can understand the context of the code.

Why is my start method undefined for the timer class?

import javax.swing.*;
import java.awt.FlowLayout;
import java.awt.event.*;
import java.util.*;
import javax.swing.Timer.*;
class Timer {
public static void main(String[] args) {
JFrame frame = new JFrame();
final int FIELD_WIDTH = 20;
final JTextField textField = new JTextField(FIELD_WIDTH);
frame.setLayout(new FlowLayout());
frame.add(textField);
ActionListener listener = new ActionListener() {
public void actionPerformed(ActionEvent event) {
Date now = new Date();
textField.setText(now.toString());
}
};
final int DELAY = 1000;
Timer t = new Timer();
t.start();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
It could be a syntax error, but I don't think so because I copied this program straight out of a book. The line of code, 't.start();' has an error line under it saying that the start() method is undefined. At first, I thought that the start() method didn't exist, but I looked it up in the library.
The problem is that you're declaring your own Timer class - so Timer t = new Timer() is referring to your class rather than javax.swing.Timer, and you don't declare a start method. I'm pretty sure you want to use the javax.swing.Timer class instead. So you want to remove the import javax.swing.Timer.*; line, and rename your Timer class to something else.
import javax.swing.*;
import java.awt.FlowLayout;
import java.awt.event.*;
import java.util.*;
public class TimerTest {
...
}
Having said that, you're not telling your timer to do anything...
While Skeet's Answer is correct, you can solve it another way. Change initialization of timer to
javax.swing.Timer t = new javax.swing.Timer(DELAY, listener);
t.start();
Follow the steps to make your code gets executed :
Change your class name to some other name.
Note: After changing the class name you will be getting a compilation error saying that there is an ambiguity of using the Timer class. As you have imported both the util and swing packages (These two packages contains the Timer Class).
Now Change your line of code to
Timer t = new Timer();
as
javax.swing.Timer t = new javax.swing.Timer(DELAY, listener);
t.start();

Java Stopwatch that updates the GUI every second?

I'm a Java beginner and I'm trying to build a simple stopwatch program that displays the time on a swing GUI. Making the stopwatch is easy, however I cannot find a way to make the GUI update every second and display the current time on the stopwatch. How can I do this?
Something along these lines should do it:
import java.awt.EventQueue;
import java.util.Timer;
import java.util.TimerTask;
import javax.swing.JFrame;
import javax.swing.JLabel;
/** #see https://stackoverflow.com/a/11058263/230513 */
public class Clock {
private Timer timer = new Timer();
private JLabel timeLabel = new JLabel(" ", JLabel.CENTER);
public Clock() {
JFrame f = new JFrame("Seconds");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(timeLabel);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
timer.schedule(new UpdateUITask(), 0, 1000);
}
private class UpdateUITask extends TimerTask {
int nSeconds = 0;
#Override
public void run() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
timeLabel.setText(String.valueOf(nSeconds++));
}
});
}
}
public static void main(String args[]) {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
final Clock clock = new Clock();
}
});
}
}
The timeLabel will always display the number of seconds the timer has been running.
You will need to correctly format it to display "hh:mm:ss"; one approach is shown here.
Create a container and add the label to it so that you can display it as part of the GUI.
Compare the result to this alternate using javax.swing.Timer.

Changing JButton Text Periodically

I would like to create a JButton that changes its text periodically after the first click. I'm not really familiar with Swing library. What would be a good starting point? May I update its text without an action?
Thank you.
for all periodical events in Swing I only suggest javax.swing.Timer
output by using Timer should be, for example
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.Timer;
public class CrazyButtonTimer {
private JFrame frame = new JFrame(" Crazy Button Timer");
private JButton b = new JButton("Crazy Colored Button");
private Random random;
public CrazyButtonTimer() {
b.setPreferredSize(new Dimension(250, 35));
frame.getContentPane().add(b);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
javax.swing.Timer timer = new Timer(500, new TimerListener());
timer.setInitialDelay(250);
timer.start();
}
private class TimerListener implements ActionListener {
private TimerListener() {
}
#Override
public void actionPerformed(final ActionEvent e) {
Color c = b.getForeground();
if (c == Color.red) {
b.setForeground(Color.blue);
} else {
b.setForeground(Color.red);
}
}
}
public static void main(final String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
CrazyButtonTimer crazyButtonTimer = new CrazyButtonTimer();
}
});
}
}
If you to change it on every fixed amount of time then you can use Swing Timer or Thread to do this. But for this you have to listen at least one action so that you can initialize and start it.
You can also use TimerTask class from java.util like follow:
java.util.TimerTask timerTask = new java.util.TimerTask() {
#Override
public void run() {
//change button text here using button.setText("newText"); method
}
};
java.util.Timer myTimer = new java.util.Timer();
myTimer.schedule(timerTask, 3 * 1000, 3* 1000); // This will start timer task after 3 seconds and repeat it on every 3 seconds.
I suggest you to create a timer (here you can find some doc)
Timer timer = new Timer(100,this);
Your class has to extend action listener ed implements the following method which allow you to change the text of your JButton(I called it ``button).
public void actionPerformed(ActionEvent e) {
if(e.getSource.equals(timer)){
button.setText("newText");
}
}
Luca
All the other answers fail to mention how to update non-periodically. If you need it to update irregularly, you can make a method in your GUI class called something like: updateButton(); and just call that every time you want it to change your text.
public void updateButton(String newText)
{
Button.setText(newText);
}
Just thought I'd add this in case someone wanted to set it irregularly.
If you want to change it periodically (e.g. every 5th second) you could create a new Thread which sets the text of the button to the desired value and repaints it (if necessary).

Categories