1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: Data Structures & Algorithms in JAVA: Graphics using JFrame

  1. Feb 4, 2012 #1
    1. The problem statement, all variables and given/known data

    This assignment handles topics of events and GUI-elements. It's a little game. The task: create a window with a button that randomly relocates to a different position on the screen each time it is hit. The player has to hit the button 10 times, the score is the time needed to finish this task. That's it. short and simple.


    It will be helpful to follow these steps:

    1. import packages: you will need three packages: javax.swing.*, java.awt.*, java.awt.event.* (if you are using netbeans, it is interesting NOT to import the packages, because netbeans will do so for you, reminding you at the time they are needed!)

    2. Create a class "JumpingButton", which extends JFrame.

    3. Do all the necessary things a JFrame needs (setDefaultCloseOperation etc).

    4. Set the layout (for example: getContentPane().setLayout(new GridLayout(1,1));

    5. Create a button, add it to your frame's content pane

    6. make the frame visible.

    So far you only set up the GUI for the game, no functionality is provided. But, at least, there's a button on the screen! Let's add functionality:

    7. prepare to register your program to the event-source, which is the button. You can only register to a button, when you guarantee that you are an ActionListener object. Currently, you are only a JFrame object. To implement and guarantee the functionality of an Actionlistener, you have to implement the interface "ActionListener". So: change your class declaration from "class JumpingButton extends JFrame" to "class JumpingButton extends JFrame implements ActionListener", which immediately makes netbeans complain that you didn't implement the method "actionPerformed" yet. Hence: do so. This is the method the button calls every time it is clicked! BUT: so far we didn't register. We only prepared to register.

    8. register! now that you are an ActionListener, you may register yourself to the button. Do so!

    9. The method actionPerformed" is the place to insert the code to let the button jump, see below.

    10. Test if the button jumps.

    11. Add the scoring logic: you need a counter, that increases every time your button is pressed. If it reaches 10, the time has to be measured.

    12. Measuring time: you can get the current time in milliseconds using the method "System.currentTimeMillis()". It returns a long-integer (primitive type "long"). If you call this method at the very beginning and after 15 clicks, the difference in the results is the time in milliseconds. Divide by 1000 to get the seconds, print, exit, ready.

    The following method relocates a JFrame on the screen to a random position (Toolkit and Dimension are in package java.awt):

    public void relocate(JFrame f){
    /*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);

    Next: Surround the button with 8 other buttons (=>grid 3x3) which the user is not allowed to hit!

    2. Relevant equations

    3. The attempt at a solution
    This is what I have gotten so far:

    Code (Text):

    package hw2;

    import java.awt.*;
    import java.awt.event.*;
    import java.util.Random;
    import javax.swing.*;

    public class JumpingButton extends JFrame implements ActionListener {

        JFrame frame;
        JButton button;
        JPanel panel;
        int count;
        long run;
        long run2;
        public JumpingButton() {
            frame = new JFrame ("Jumping Button");

            frame.getContentPane().setLayout(new BorderLayout());
            frame.setPreferredSize(new Dimension(600,400));

          panel = new JPanel();
           button = new JButton("Click Here");
       //    frame.getContentPane().add(b, "Center");
           button.setPreferredSize(new Dimension (100,50));

        public void actionPerformed(ActionEvent e) {
       Random rand = new Random();
      Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    //Dimension windowSize1 = button.getSize();
    //Dimension windowSize2 = panel.getSize();
      Dimension windowSize = panel.getSize();
    int x = rand.nextInt(screenSize.width - windowSize.width);
    int y = rand.nextInt(screenSize.height - windowSize.height);


        run = System.currentTimeMillis(); }

        run2= System.currentTimeMillis();

    In my main class, I have:

    Code (Text):

    package hw2;

    import java.awt.Dimension;

    public class HW2 {

        public static void main(String[] args) {

            JumpingButton jb = new JumpingButton();
            jb.setPreferredSize(new Dimension(600,400));



    When I run my program, it runs for two clicks and then the button just disappears. I'm not entirely well-versed in JAVA so I do not know why this failed to run as intended.
    Last edited: Feb 4, 2012
  2. jcsd
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook

Can you offer guidance or do you also need help?
Draft saved Draft deleted