So I’m working on a project for one of my classes and I’m using the ActionListener interface (Java). I need to make the button that appears on screen jump to a different location. The actionPerformed method is where I’m having an issue. I’m not sure what to do there. Any ideas? Thanks in advance!
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package assignment2;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
/**
*
* @author tuc73318
*/
public class JumpingButton extends JFrame implements ActionListener
{
JButton button;
public JumpingButton()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new GridLayout(1,1));
button = new JButton("Click this!");
getContentPane().add(button);
pack();
setVisible(true);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
}
public void relocate(JFrame f)
{
Random rand = new Random();
/*If this function is called, it will relocate the window to a new random position on the screen*/
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension windowSize = f.getSize();
int x = rand.nextInt(screenSize.width - windowSize.width);
int y = rand.nextInt(screenSize.height - windowSize.height);
f.setLocation(x,y);
}
}
So I got the button to jump, but now I need a counter and timer. I have some code to handle that, but it doesn’t work. Any help would be greatly appreciated.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package assignment2;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
/**
*
* @author tuc73318
*/
public class JumpingButton extends JFrame implements ActionListener
{
JButton button;
int timesClicked = 0;
public JumpingButton()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(new GridLayout(1,1));
button = new JButton("Click this!");
getContentPane().add(button);
button.setActionCommand("press");
pack();
setVisible(true);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
timesClicked++;
long startTime = System.currentTimeMillis();
JFrame f = (JFrame) new JumpingButton();
Random rand = new Random();
/*If this function is called, it will relocate the window to a new random position on the screen*/
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension windowSize = f.getSize();
int x = rand.nextInt(screenSize.width - windowSize.width);
int y = rand.nextInt(screenSize.height - windowSize.height);
f.setLocation(x,y);
if(timesClicked == 10)
{
long endTime = System.currentTimeMillis();
long finalTime = (endTime - startTime)/(1000);
System.out.println("Your score is: " + finalTime + "s!");
System.exit(0);
}
}
}