Why is my start method undefined for the timer class? - java

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();

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
}
}

Getting null textarea inside a frame when calls it from outside the class inside same package using new keyword

I crated a Frame which have a panel inside it and the panel have a textarea inside it. Now i created a constructor which makes the frame visible for some time and after that it is set as invisible. Time for which it is visible it shows some message.
When i run the constructor code inside the main method of outputDisplay class it shows the text massage
but when i call it inside other class by using new outputDisplay(String ip, int time) then only the frame appers but with no text inside it.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
public class OutputDisplay {
JFrame frame;
JPanel panel;
JTextArea area;
Font font;
OutputDisplay(String ip,int time) throws InterruptedException{
frame = new JFrame("Warning");
frame.setLocation(400, 220);
panel = new JPanel();
area = new JTextArea();
font = new Font("Aharoni", Font.BOLD, 16);
area.setFont(font);
area.setForeground(Color.RED);
area.setSize(200, 200);
int j=0;
String[] t = {ip};
for(int i=0;i<t.length;i++){
area.append(t[i]+"\n");
}//for
//area.setText(ip);
panel.add(area);
panel.setLayout(new BoxLayout(panel,BoxLayout.Y_AXIS));
frame.getContentPane().add(BorderLayout.CENTER, panel);
frame.pack();
frame.setSize(600, 200);
frame.setVisible(true);
Thread.sleep(time);
j++;
if(j==1){
frame.setVisible(false);
}//if
frame.setResizable(false);
}//constructor
}//Class
Thread.sleep(time); Dont do it (you're blocking the EDT). Use a Swing Timer
Timer timer = new Timer(time, new ActionListener(){
public void actionPerformed(ActionEvent e) {
frame.setVisible(false);
}
});
timer.start();
See
The Use of Multiple JFrames, Good/Bad Practice?
Concurrency with Swing
"When i run the constructor code inside the main method of outputDisplay class it shows the text massage "
You are probably doing
public static void main (String[] args) {
new OutputDisplay();
}
This is not run on the Event Dispatch Thread, (But wrong). If you ran it on the EDT, like you're supposed to (see Initial Threads, it will not work
public static void main (String[] args) {
SwingUtilities.invokeLater(new Runnable(){
new OutputDisplay(); <==== Create on EDT
}); WON'T WORK!!
}
"but when i call it inside other class by using new outputDisplay(String ip, int time) then only the frame appers but with no text inside it."
JBUtton button = new JButton("Button");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
new OurputDisplay(); <===== Created on EDT!!
}
});
Whether or not you start the application on the Event thread, all Component Events are dispatch on this thread, so when you press a button to try and open the new frame, this is create the frame on the EDT. Same problem as when running the OutputDisplay on its own with SwingUtilities.invokeLater
The answer is that the second way, you are running this on the UI thread. So when you do your sleep call, nothing is displayed in the gui BECAUSE YOU'VE PUT THE GUI TO SLEEP. The solution is to use a javax.swing.Timer.
... Not meaning to yell, just want to highlight the source of the problem

Java. Could not find or load main class

I know this has been asked before...Just none of the answers on other questions worked.
When I try to run this in eclipse I just get Error: Could not find or load main class Hey.Init in the console. "Hey" is the package.
I can post the third class I just don't think it's relevant.
package Hey;
import javax.swing.SwingUtilities;
public class Init {
static Runnable createGui = new Runnable(){
public void run(){
new Gui();
}
};
public static void main(String[] args){
SwingUtilities.invokeLater(createGui);
}
}
Other Class:
package Hey;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class Gui {
private JFrame frame = new JFrame("Title");
private JButton button;
public Gui(){
frame.setLayout(new FlowLayout());
button = new JButton("DON'T HIT ME!!!");
button.addMouseListener(new Yo());
}
}
Weird as i do not see any issue in here. However it could be that you are trying to run a file which is not set as "main project" and effectively may not have a main method, if you know what i mean. Also on the side note
#Override
public void run(){
Gui gui = new Gui();
}
And one more thing why not implement the interface ?
public class Hello implements Runnable{
....
}

My DigitalClock not working

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);

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