Timer and JSlider with images - java

This is part of my code and it doesn't work because it keeps on saying it cannot find the symbol in my ActionListener. I don't know how to make it work.
So basically what I'm trying to do is make the images from 1-8.png move depending on where the slider lands and IDK how to:
private static JLabel value;
private static ImageIcon image;
private static Timer timer;
private static final int delay = 2000;
private static int newDelay;
private static int i = 1;
timer = new Timer(delay, new ActionListener() {
public void actionPerformed(ActionEvent e) {
// makes the image at i appear and then goes to 2 and so on until i i = 8 and will return a 1 after. Will keep on doing so
value.setIcon(new ImageIcon(i + ".png"));
i++;
if(i == 8) {
i = 1;
}
}
});
timer.start();
}
private static class SliderChange implements ChangeListener {
public void stateChanged(ChangeEvent event) {
JSlider source = (JSlider) event.getSource();
// while it is adjusting timer stops and gets the value of where the slider hits and the newDelay will be the new timer time. (So if they drag slider to 6, delay(which is 2000) will be divided by 6 to get new time
if (!source.getValueIsAdjusting()) {
timer.stop();
value.setIcon(new ImageIcon(i + ".png"));
newDelay = (delay/(int)source.getValue());
timer = new Timer(newDelay, new Actionlistener());
timer.start();
}
}
}
But this doesn't work. How can I fix it?
It points to this line saying there is an error:
timer = new Timer(newDelay, new Actionlistener());

I'm not sure it's really necessary to recreate the Timer each time. Instead, stop it, set it's delay property and restart it instead
private static class SliderChange implements ChangeListener {
public void stateChanged(ChangeEvent event) {
JSlider source = (JSlider) event.getSource();
// while it is adjusting timer stops and gets the value of where the slider hits and the newDelay will be the new timer time. (So if they drag slider to 6, delay(which is 2000) will be divided by 6 to get new time
if (!source.getValueIsAdjusting()) {
timer.stop();
value.setIcon(new ImageIcon(i + ".png"));
newDelay = (delay/(int)source.getValue());
timer.setDelay(newDelay);
timer.start();
}
}
}
The problem is timer = new Timer(newDelay, new Actionlistener()); is trying to create an instance of a interface without the implementing the requirements of the interface, which is confusing the compiler

Related

Not showing Swing component when running before or in the game loop

I'm actually trying to fix a problem with the component of JFrame that don't want to show up when I run my game loop (see the question after the code). I have reduced the code at the minimum possible for you to get what I mean fast:
Run.class
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
Game game = new Game();
game.loop();
}
});
}
Game.class
private Frame frame;
private HashMap<String,ActionListener> actions;
private HashMap<String,Image> ressources;
public Game() {
this.setActions();
this.setRessources();
frame = new Frame(actions,ressources);
}
public void loop() {
double FPS = 60;
double UPS = 60;
long initialTime = System.nanoTime();
final double timeU = 1000000000 / UPS;
final double timeF = 1000000000 / FPS;
double deltaU = 0, deltaF = 0;
int frames = 0, ticks = 0;
long timer = System.currentTimeMillis();
boolean running = true;
boolean RENDER_TIME = false;
while (running) {
...code for update, render, with a fps control
}
}
Frame.class
public Frame(HashMap<String,ActionListener> actions, HashMap<String,Image> ressources) {
this.setTitle(Constants.GAME_NAME);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(Constants.GAME_SIZE_X, Constants.GAME_SIZE_Y);
this.setLayout(new FlowLayout());
JButton myButton = new JButton("My Button");
this.add(myButton);
this.revalidate();
this.repaint();
this.setVisible(true);
}
It's not the complete code because I don't want to give a useless thing. So here, my problem is:
If I run this code, the button not going to show up in the frame. But if I comment game.loop() in the Run.class, the windows show the button. And I don't understand WHY?
I have been trying for a few days to figure it out. I need some help for this one. Alone I'm afraid I will not find out.
To avid blocking the Event Dispatching Thread by running a long process you can use swing Timer which can handle the "looping" for you :
ActionListener animate = e -> {
game.oneFrame();
panel.repaint();
};
timer = new Timer(50, animate);
timer.start();
public void oneFrame(){
//update what is needed for one "frame"
}
For more help post mcve.

Getting value from JRadioButton

I'd like to change value of my variable "name" when I select right button and click "ok" on my JRadio Frame.
For example when i select r1 and hit "ok" I'd like to have name=="Fast" in the entire package.
package Snake;
public class Radio extends JFrame {
private int delay = 100;
private String name;
JTextField t1;
JButton b;
JRadioButton r1, r2;
JLabel l;
public void selectSpeed() {
b = new JButton("Ok");
r1 = new JRadioButton("Fast");
r2 = new JRadioButton("Slow");
l = new JLabel("Speed: ");
ButtonGroup bg = new ButtonGroup();
bg.add(r1);
bg.add(r2);
add(b);
add(r1);
add(r2);
add(l);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (r1.isSelected()) {
name = "Fast";
} else {
name = "Slow";
}
l.setText("Speed: " + name); // name=="Fast" when r1 is selected
} // name=="Slow" when r2 is selected
});
if (name == "Fast") { // and now name is empty...
delay = 50;
}
if (name == "Slow") {
delay = 500;
}
setLayout(new FlowLayout());
setSize(400, 400);
setVisible(true);
}
public int setSpeed() {
selectSpeed();
return delay;
}
}
If you want to change the delay on button click, You need to write the logic in the ActionListener itself because the code you have written to change the delay will run only once and that too at the start of the execution of your program and at that time, name will be empty.
Then when ever you click the button, It will only execute the ActionListener So delay will not be changed at any time. And other mistake you are making is that you are comparing Strings in wrong way. For more information take a look at it How do I compare Strings in Java?
To change delay dynamically on button click, you need to change it in the ActionListener.
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (r1.isSelected()) {
name = "Fast";
delay = 50;
} else {
name = "Slow";
delay = 500;
}
l.setText("Speed: " + name); // name=="Fast" when r1 is selected
} // name=="Slow" when r2 is selected
});
You need to do it in your JRadioButton listener. For example, like here, at first you change the variable "name" and later in the current listener you check conditions, but you need remember that to compare the strings you need to use "equals":
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (r1.isSelected()) {
name = "Fast";
} else {
name = "Slow";
}
l.setText("Speed: " + name); // name=="Fast" when r1 is selected
if (name.equals("Fast")) { // and now name is empty...
delay = 50;
}
if (name.equals("Slow")) {
delay = 500;
}
} // name=="Slow" when r2 is selected
});
Well I see my mistake now, Thank you.
But it still does not work the way I like. I'd like to change the "delay" value every time I select right button on JRadio and hit "ok" and with this changed value I'd like to go to the other class.
There is the code of a class where I need value of "delay":
package Snake;
public class Gameplay extends Paint implements KeyListener, ActionListener {
private Timer timer;
private int q = 0;
Radio radio = new Radio();
public Gameplay() {
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
timer = new Timer(radio.selectSpeed(), this); //here i need flexible "delay" value
timer.start();
}

Preloading images to use as JLabel icon

I want to have a simple JFrame with a JLabel (to show images as an icon) and a JSlider (to switch between 40 images).
When I load the new images on a StateChange event of the slider, the program gets very slow, especially when I slide fast.
So I was thinking of preloading the 40 images and replacing them via the slider. Is this smart and possible?
I assume, you have something like this:
public class MyClass {
// other declarations
private JLabel label;
// other methods
public void stateChange(ChangeEvent e) {
label.setIcon(new ImageIcon(...)); // here is code to determine name of the icon to load.
timer = null;
}
}
What you need is to change your code as following:
public class MyClass {
// other declarations
private JLabel label;
private Timer timer; // javax.swing.Timer
// other methods
public void stateChange(ChangeEvent e) {
if (timer != null) {
timer.stop();
}
timer = new Timer(250, new ActionListener() {
public void actionPerformed(ActionEvent e) {
label.setIcon(new ImageIcon(...)); // here is code to determine name of the icon to load.
timer = null;
}
});
timer.setRepeats(false);
timer.start();
}
}

Can you cancel a specific TimerTask in Java?

I'm creating a game that ends if you haven't reached a certain point by the time the timer reaches zero. It currently works and I can create multiple TimerTasks at one time, but I cannot cancel them. Currently, clicking the button resets the timer (on the display) but will still run in the background and end the program when it reaches zero (even though it shouldn't be running). Here's the code for the ActionListener that starts each timer.
public class Game implements Runnable {
private int currentScore, difficulty, level, highscore, x, y;
private boolean playMusic, playClicks, gameRunning;
private boolean stopLastTimer = false;
JFrame gameFrame;
Data data;
JButton target;
Thread t;
JLabel score;
Timer globalTimer = new Timer();
JLabel timer;
ActionListener clickedAction = new ActionListener(){
public void actionPerformed(ActionEvent ae) {
stopLastTimer = true;
t.interrupt();
currentScore++;
score.setText("Score: " + currentScore);
//playClickSound();
globalTimer.schedule(new TimerTask(){
double second = 2.0;
#Override
public void run() {
second = second - 0.1;
if(stopLastTimer) {
this.cancel(); stopLastTimer = false; } //should end old timer here
if(second == 0.0) {
this.cancel();
gameStop();
}
second = limitPrecision(Double.toString(second), 1);
timer.setText(second + "s");
}
},0, 100);
}
};
Don't use a TimerTask.
Instead you should be using a javax.swing.Timer for the animation. A Swing Timer has a stop() method.
The source of the ActionEvent will be the Timer itself.
Read the section from the Swing tutorial on How to Use Timer for more information and working examples.

Java Timer usage with JButtons

I have problem that I don't understand, how to correctly use the Java timer with JButton.
The idea of what I need -
When I click on JButton with text "0" then starts the timer counting from two seconds till zero.
When button is released program checks the situation:
if timer now is 0 then it shows in JTextField sign "+", else it shows "0".
Here is my code of program. Can someone please add the things that I need to make the program work like the idea I want?
public class DialPanel extends JPanel {
private MainFrame frame;
public DialPanel(MainFrame frame) {
this.frame = frame;
this.setLocation(0, 90);
this.setSize(300, 290);
this.setLayout(null);
this.setBackground(color);
this.initContent();
}
// -------------------------------------------------------------------------
private JButton btnNumZero;
private JTextField txfNumber;
private void initContent() {
txfNumber = new JTextField();
this.add(txfNumber);
txfNumber.setSize(190, 30);
txfNumber.setLocation(30, 0);
txfNumber.setFocusable(false);
txfNumber.addActionListener(controller);
btnNumZero = new JButton();
this.add(btnNumZero);
btnNumZero.setText("0");
btnNumZero.setFocusable(false);
btnNumZero.setSize(30, 30);
btnNumZero.setLocation(10, 10);
btnNumZero.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
//Start someTimer countdown from two seconds
}
});
btnNumZero.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
//Stop someTimer
//if someTimer == 0 seconds then do this line:
txfNumber.setText("+");
//else do this line:
txfNumber.setText("0");
}
});
}
}
Excuse me if there is some unnecessary error with code. I deleted and changed a lot of things from the real one code so that this could be more understandable and clear for reading.
Instead of using a Timer, you may want to just make use of System.currentTimeMillis(). The Timer may not be a timer in the sense you are looking for, as a stopwatch type object.
You could do something like this
long startTime;
long endTime;
btnNumZero.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
startTime = System.currentTimeMillis();
}
});
btnNumZero.addMouseListener(new MouseAdapter() {
#Override
public void mouseReleased(MouseEvent e) {
endTime = System.currentTimeMillis();
long difference = endTime - startTime;
if (difference > 2000)
txfNumber.setText("+");
else
txfNumber.setText("0");
}
});

Categories

Resources