Data Structures & Algorithms in JAVA: Graphics using JFrame

In summary, the conversation discusses creating a simple game using events and GUI elements. The task is to create a window with a button that randomly relocates each time it is clicked. The player must click the button 10 times and the score is based on the time needed to complete the task. The conversation provides steps to follow, such as importing packages, creating a class that extends JFrame, setting the layout, creating a button, and registering the program to the button. It also includes instructions for adding functionality and scoring logic. The conversation also provides a method to relocate the JFrame to a random position on the screen. There are some issues with the code provided, such as creating multiple JFrame objects, setting the location of the wrong component, and not properly
  • #1
skylit
7
0

Homework Statement



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.

HELP:

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);
f.setLocation(x,y);
}

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

Homework Equations


The Attempt at a Solution


This is what I have gotten so far:

Code:
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.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        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));
       button.addActionListener(this);
       
       panel.add(button);
        getContentPane().add(panel);
        
            pack();
            
            setVisible(true);
        }

    @Override
    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);
panel.setLocation(x,y);
count++;

System.out.println(count);

if(count==1){
    run = System.currentTimeMillis(); }

if(count==10){
    run2= System.currentTimeMillis();
    
    System.exit(0);
    
}
}
    }

In my main class, I have:

Code:
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:
Physics news on Phys.org
  • #2


There are a few issues with your code that may be causing the button to disappear after two clicks:

1. You are creating a new JFrame within your JumpingButton class, but you are also creating a JFrame in your main class and setting its content pane to the JumpingButton object. This could be causing conflicts and unexpected behavior. It would be better to just have one JFrame in your main class and add the JumpingButton object to its content pane.

2. In your actionPerformed method, you are setting the location of the panel instead of the button. This means that the button is moving off the screen and eventually disappearing. You should change the line "panel.setLocation(x,y);" to "button.setLocation(x,y);".

3. You are not using the "run" and "run2" variables that you declared in your JumpingButton class. These variables are meant to store the times when the button is first clicked and when it reaches 10 clicks, but you are not using them anywhere in your code. You should use these variables to calculate the time it takes to click the button 10 times and print it out at the end.

4. You are not setting the size of your JFrame in your main class. You should add the line "jb.setSize(new Dimension(600,400));" after creating your JumpingButton object to ensure that the JFrame is the correct size.

I would also recommend organizing your code a bit better by separating the GUI setup and the functionality into different methods. This will make your code easier to read and debug. Overall, your code looks good and you are on the right track, but these small changes should help fix the issues you are experiencing.
 

What is a data structure?

A data structure is a way of organizing and storing data in a computer so that it can be accessed and used efficiently. It provides a framework for organizing and manipulating data in a specific way that makes it easier to retrieve and use the data as needed.

What is an algorithm?

An algorithm is a set of step-by-step instructions for solving a problem or performing a task. It is a sequence of well-defined, unambiguous instructions that can be executed by a computer to solve a problem or complete a task.

How is JAVA used in graphics programming?

JAVA is used in graphics programming through the use of the JFrame class, which is a part of the Java Swing library. JFrame provides a framework for creating and managing windows, and allows for the creation of graphical user interfaces (GUIs) for applications.

What are the benefits of using data structures and algorithms in JAVA?

Using data structures and algorithms in JAVA can help improve the efficiency and performance of programs. It allows for the manipulation and organization of data in a way that makes it easier to retrieve and use, ultimately leading to more streamlined and optimized code.

What are some common data structures used in JAVA programming?

Some common data structures used in JAVA programming include arrays, linked lists, stacks, queues, trees, and hash tables. Each data structure has its own unique properties and uses, and choosing the right one can greatly impact the efficiency and effectiveness of a program.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
1
Views
950
  • Programming and Computer Science
Replies
14
Views
3K
  • Programming and Computer Science
Replies
1
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
4
Views
3K
  • Engineering and Comp Sci Homework Help
Replies
2
Views
5K
  • Programming and Computer Science
Replies
5
Views
1K
  • Programming and Computer Science
Replies
1
Views
2K
  • Programming and Computer Science
Replies
2
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
4
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
2K
Back
Top