Eventually got the balls to move, but the app doesn't execute perfectly and I'm still unsure about the run() method setup... I don't think I need it but it's part of the assignment. Please let me know if there's a better way.
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class BouncingBallApp extends JFrame
{
//start of main method
public static void main(String[] args)
{
//crate container
Container container = new Container();
//crate BouncingBallApp instance
BouncingBallApp bBalls = new BouncingBallApp();
//set the window closing feature(close with X click)
bBalls.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//crate boucing ball panel(BBP) instance and add
BouncingBallPanel BBP = new BouncingBallPanel();
container.add(BBP);
//make the BBP the MouseListner
bBalls.addMouseListener(BBP);
//set window background and size
bBalls.setBackground(Color.WHITE);
bBalls.setSize(400, 300);
BBP.setSize(400, 300);
BBP.setLayout(null);
bBalls.setContentPane(BBP);
//set window visible
bBalls.setVisible(true);
}//end of main method
}//end of Class BouncingBall App
class BouncingBallPanel extends JPanel implements MouseListener
{
//create an empty array for 20 Ball objects
public Ball[] array;
private int count = 0;
Random generator = new Random();
public BouncingBallPanel()
{
array = new Ball[20];
}
public void mouseClicked(MouseEvent event)
{
array[count] = new Ball(this);
count++;
if( count == 1)
{
final Runnable update = new Runnable()
{
public void run()
{
for (int j = 0; j < array.length; j++)
{
if(array[j] != null)
{
array[j].move();
}//end of if
}//end of for
}//end of run method
};//end of runnalbe update
(new Thread(new Ball(this))).start();
Runnable graphic = new Runnable()
{
public void run()
{
while(true)
{
try
{
EventQueue.invokeLater(update);
Thread.sleep(generator.nextInt(10 +100));
}catch (InterruptedException exp){}
}//end of while
}//end of run
};//end of runnable
new Thread(graphic).start();
}//end of if
}//end of mouseClicked method
//empty interfaces for mouse events
public void mouseExited(MouseEvent event){}
public void mouseReleased(MouseEvent event){}
public void mouseEntered(MouseEvent event){}
public void mousePressed(MouseEvent event){}
//paint component method
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
//loop for each ball and draw all balls in array
for(int i = 0; i < array.length; i++)
{
if(array[i] != null)
{
g2d.setColor(array[i].getColor());
g2d.fillOval((int)array[i].getX(), (int)array[i].getY(), (int)array[i].getDiameter(), (int)array[i].getDiameter());
}
}//end of for loop
}//end of paintComponent loop
}//end of Class BouncingBallPanel
class Ball implements Runnable
{
//set up variables
private double x;
private double y;
private int deltaX;
private int deltaY;
private double diameter;
private Color color;
BouncingBallPanel BBP2;
Random random = new Random();
public Ball(BouncingBallPanel a)
{
x = random.nextInt(400);
y = random.nextInt(300);
deltaX = 1 + random.nextInt(10);
deltaY = 1 + random.nextInt(10);
diameter = 5 + random.nextInt(20);
color = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
BBP2 = a;
}// end of constructor
public double getX()
{
return x;
}
public double getY() {
return y;
}
public double getDiameter() {
return diameter;
}
public Color getColor() {
return color;
}
public void move() {
x += deltaX;
y += deltaY;
if (x > 400 - getDiameter()|| x <0)
{
deltaX = -deltaX;
}
if (y > 300 - getDiameter() || y < 0)
{
deltaY = -deltaY;
}
}// end of method move
#Override
public void run()
{
while(true)
{
move();
BBP2.repaint();
try{
Thread.currentThread().sleep(10 + random.nextInt(100));
}catch(InterruptedException exp){}
}//end of while
}//end of run method
}//end of Ball
Two problems:
You never create threads for the balls. Just making an object Runnable does not implicitly create a thread. You need something like this in the constructor:
new Thread(this).start();
In the Swing event model, using Timer is better than background threads. Using threads, you will see graphical artifacts if an object moves while the window is being painted.
Related
This is my frog class which is being called by a GUI class.
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
public class Frog implements Runnable {
private int x, y, dx, dy;
private int coordinates[]=new int[2];
private boolean hungry;
private JLabel jLabel;
private ImageIcon image;
private String name;
public Frog() {
}
public Frog(String name, boolean hungry) {
image = new ImageIcon("images/frog.jpeg");
jLabel = new JLabel(image);
setName(name);
setHungry(hungry);
setCoordinates();
}
private void setName(String name) {
this.name=name;
}
public int[] getCoordinates() {
return coordinates;
}
public boolean isHungry() {
return hungry;
}
public void setHungry(boolean hungry) {
this.hungry = hungry;
}
public void display(Graphics paper) {
paper.setColor(Color.black);
paper.drawOval(x, y, dx, dx);
}
public void setCoordinates() {
for(int i = 0; i < 2; i++) {
Random rand = new Random();
int p = rand.nextInt(100);
coordinates[i] = p;
}
setX(coordinates[0]);
setY(coordinates[1]);
}
public void move() {
x = (int)Math.random() * 350;
y = (int)Math.random() * 350;
dx=20;
dx=20;
x += dx;
y += dy;
if (x > 800 || x < 0)
dx=-dx;
if (y > 600 || y < 0)
dy=-dy;
}
public void setDx(int dx) {
this.dx = dx;
}
public void setDy(int dy) {
this.dy = dy;
}
public void setX(int x){
this.x = x;
}
public void setY(int y){
this.y = y;
}
public void run() {
while(!hungry) {
move();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
I have created this class to move a frog object randomly but when I call the move method nothing is happening. I want the frog on a JPanel to randomly move around the screen. I have another class which uses the frog object.
It is used from a main class containing the following:
public void actionPerformed(ActionEvent event) {
if (event.getSource() == MakePet) {
String petName = namePlace.getText();
frog = new Frog(petName,false);
panel.add(pet);
panel.add(prey);
frog.move();
Thread fro = new Thread(frog);
fro.start();
}
}
public static void main(String[] args) {
GUI demo = new GUI();
demo.setSize(520,720);
demo.createGUI();
demo.show();
}
For an example of timer based animation, have a look at http://www.java2s.com/Code/Java/2D-Graphics-GUI/Timerbasedanimation.htm
Another example of timer based animation, where Swing components are used to draw images on a JPanel was given Jérôme's comment: Randomly moving images on a JPanel
If you require having multiple frogs with their own threads of control, then you will need to handle synchronization. Otherwise I would simply call move from the timer before repainting the panel. And then change move:
public void move() {
if (!hungry) {
return;
}
...
}
Set the timer's interval appropriately based on the framerate you are looking to achieve. The below is based on the answer from the question Jérôme linked to:
Timer t = new Timer(1000 / DESIRED_FRAMERATE, (event) -> {
frogs.forEach(Frog::move);
panel.repaint();
});
Note that this is Java 8 using lambdas.
The above in pre-Java 8:
Timer t = new Timer(1000 / DESIRED_FRAMERATE, new ActionListener() {
public void actionPerformed(ActionEvent event) {
for (Frog frog : frogs) {
frog.move();
}
panel.repaint();
}
});
You should create the Timer in the initialization code of your JFrame or JPanel. If you have a class extending JPanel, you don't need to reference panel when calling repaint if the Timer is inside that class. Also, here I am guessing you have a collection of Frog objects, typically a list, called frogs. If there's only ever one frog, you don't need the loop. Frog's display method needs to be called from the JPanel's paint method, so I am guessing you have a class extending JPanel.
These are the specific instruction but they are kind of confusing to me (are the instructions confusing/ambiguous or am I just not getting it?)
write a method public static void draw shooter(Graphics g, Color c);
call draw shooter using the shooter color as the last parameter in drawAll(?)
test the program you should see a red disk centered near the bottom of the screen(?)
import java.awt.*;
public class Project2{
public static final int PANEL_WIDTH = 300;
public static final int PANEL_HEIGHT = 300;
public static final int SLEEP_TIME = 50;
public static Color SHOOTER_COLOR = Color.RED;
public static Color BACKGROUND_COLOR = Color.WHITE;
public static final int SHOOTER_SIZE = 20; //diameter of the shooter
public static final int GUN_SIZE = 10; //length og the gun
public static final int SHOOTER_POSITION_Y = PANEL_HEIGHT - SHOOTER_SIZE;
public static final int SHOOTER_INITIAL_POSITION_X = 150;
int shooterPosition;
public static void initialize(){
int shooterPositionX = SHOOTER_INITIAL_POSITION_X;
}
public static void main(String[] args) {
DrawingPanel panel = new DrawingPanel(PANEL_WIDTH, PANEL_HEIGHT);
Graphics g = panel.getGraphics( );
initialize();
startGame(panel, g);
drawShooter(g, SHOOTER_COLOR);
}
public static void drawShooter(Graphics g, Color C){
g.setColor(Color);
g.fillOval(shooterPosition, SHOOTER_POSITION_Y, SHOOTER_SIZE, SHOOTER_SIZE);
}
public static void drawAll(Graphics g){
g.drawString("Project 2 by Jasmine Ramirez", 10, 15);
}
public static void startGame(DrawingPanel panel, Graphics g) {
for (int i = 0; i <= 10000; i++) {
panel.sleep(SLEEP_TIME);
drawAll(g);
}
}
}
this is my code I guessed that I needed to draw and color in a circle inside the method but I am getting errors with the g.setColor inside the method and I'm not sure what the second step means. Thanks just started learning to program.
Drawing Panel
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.ArrayList;
public class DrawingPanel implements ActionListener {
private static final String versionMessage =
"Drawing Panel version 1.1, January 25, 2015";
private static final int DELAY = 100; // delay between repaints in millis
private static final boolean PRETTY = false; // true to anti-alias
private static boolean showStatus = false;
private static final int MAX_KEY_BUF_SIZE = 10;
private int width, height; // dimensions of window frame
private JFrame frame; // overall window frame
private JPanel panel; // overall drawing surface
private BufferedImage image; // remembers drawing commands
private Graphics2D g2; // graphics context for painting
private JLabel statusBar; // status bar showing mouse position
private volatile MouseEvent click; // stores the last mouse click
private volatile boolean pressed; // true if the mouse is pressed
private volatile MouseEvent move; // stores the position of the mouse
private ArrayList<KeyInfo> keys;
// construct a drawing panel of given width and height enclosed in a window
public DrawingPanel(int width, int height) {
this.width = width;
this.height = height;
keys = new ArrayList<KeyInfo>();
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
statusBar = new JLabel(" ");
statusBar.setBorder(BorderFactory.createLineBorder(Color.BLACK));
statusBar.setText(versionMessage);
panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
panel.setBackground(Color.WHITE);
panel.setPreferredSize(new Dimension(width, height));
panel.add(new JLabel(new ImageIcon(image)));
click = null;
move = null;
pressed = false;
// listen to mouse movement
MouseInputAdapter listener = new MouseInputAdapter() {
public void mouseMoved(MouseEvent e) {
pressed = false;
move = e;
if (showStatus)
statusBar.setText("moved (" + e.getX() + ", " + e.getY() + ")");
}
public void mousePressed(MouseEvent e) {
pressed = true;
move = e;
if (showStatus)
statusBar.setText("pressed (" + e.getX() + ", " + e.getY() + ")");
}
public void mouseDragged(MouseEvent e) {
pressed = true;
move = e;
if (showStatus)
statusBar.setText("dragged (" + e.getX() + ", " + e.getY() + ")");
}
public void mouseReleased(MouseEvent e) {
click = e;
pressed = false;
if (showStatus)
statusBar.setText("released (" + e.getX() + ", " + e.getY() + ")");
}
public void mouseEntered(MouseEvent e) {
// System.out.println("mouse entered");
panel.requestFocus();
}
};
panel.addMouseListener(listener);
panel.addMouseMotionListener(listener);
new DrawingPanelKeyListener();
g2 = (Graphics2D)image.getGraphics();
g2.setColor(Color.BLACK);
if (PRETTY) {
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setStroke(new BasicStroke(1.1f));
}
frame = new JFrame("Drawing Panel");
frame.setResizable(false);
try {
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // so that this works in an applet
} catch (Exception e) {}
frame.getContentPane().add(panel);
frame.getContentPane().add(statusBar, "South");
frame.pack();
frame.setVisible(true);
toFront();
frame.requestFocus();
// repaint timer so that the screen will update
new Timer(DELAY, this).start();
}
public void showMouseStatus(boolean f) {
showStatus = f;
}
public void addKeyListener(KeyListener listener) {
panel.addKeyListener(listener);
panel.requestFocus();
}
// used for an internal timer that keeps repainting
public void actionPerformed(ActionEvent e) {
panel.repaint();
}
// obtain the Graphics object to draw on the panel
public Graphics2D getGraphics() {
return g2;
}
// set the background color of the drawing panel
public void setBackground(Color c) {
panel.setBackground(c);
}
// show or hide the drawing panel on the screen
public void setVisible(boolean visible) {
frame.setVisible(visible);
}
// makes the program pause for the given amount of time,
// allowing for animation
public void sleep(int millis) {
panel.repaint();
try {
Thread.sleep(millis);
} catch (InterruptedException e) {}
}
// close the drawing panel
public void close() {
frame.dispose();
}
// makes drawing panel become the frontmost window on the screen
public void toFront() {
frame.toFront();
}
// return panel width
public int getWidth() {
return width;
}
// return panel height
public int getHeight() {
return height;
}
// return the X position of the mouse or -1
public int getMouseX() {
if (move == null) {
return -1;
} else {
return move.getX();
}
}
// return the Y position of the mouse or -1
public int getMouseY() {
if (move == null) {
return -1;
} else {
return move.getY();
}
}
// return the X position of the last click or -1
public int getClickX() {
if (click == null) {
return -1;
} else {
return click.getX();
}
}
// return the Y position of the last click or -1
public int getClickY() {
if (click == null) {
return -1;
} else {
return click.getY();
}
}
// return true if a mouse button is pressed
public boolean mousePressed() {
return pressed;
}
public synchronized int getKeyCode() {
if (keys.size() == 0)
return 0;
return keys.remove(0).keyCode;
}
public synchronized char getKeyChar() {
if (keys.size() == 0)
return 0;
return keys.remove(0).keyChar;
}
public synchronized int getKeysSize() {
return keys.size();
}
private synchronized void insertKeyData(char c, int code) {
keys.add(new KeyInfo(c,code));
if (keys.size() > MAX_KEY_BUF_SIZE) {
keys.remove(0);
// System.out.println("Dropped key");
}
}
private class KeyInfo {
public int keyCode;
public char keyChar;
public KeyInfo(char keyChar, int keyCode) {
this.keyCode = keyCode;
this.keyChar = keyChar;
}
}
private class DrawingPanelKeyListener implements KeyListener {
int repeatCount = 0;
public DrawingPanelKeyListener() {
panel.addKeyListener(this);
panel.requestFocus();
}
public void keyPressed(KeyEvent event) {
// System.out.println("key pressed");
repeatCount++;
if ((repeatCount == 1) || (getKeysSize() < 2))
insertKeyData(event.getKeyChar(),event.getKeyCode());
}
public void keyTyped(KeyEvent event) {
}
public void keyReleased(KeyEvent event) {
repeatCount = 0;
}
}
}
1st Error
In your drawShooter() method you do:
g.setColor(Color)
This is incorrect, since you need to pass an instance of the class Color not the class itself.
So instead use this:
g.setColor(C);
2nd Error
change the shooterPosition to static so that it can be accessed by a static method.
I assume that the method initialize() is also wrong because you are declaring a new shooterPosition int for no reason so do these changes:
int shooterPosition;
To:
public static int shooterPosition;
And
public static void initialize(){
int shooterPositionX = SHOOTER_INITIAL_POSITION_X;
}
To:
public static void initialize() {
shooterPosition = SHOOTER_INITIAL_POSITION_X;
}
3rd Error
In startGame() you are looping for 10000 times and each time you are waiting for a bit more than 1/20th of a second, which means that you will have to wait for almost 10 minutes until the red circle is drawn. So you have two options.
1st option: decrease the amount of iterations or even better remove the loop.
public static void startGame(DrawingPanel panel, Graphics g) {
for (int i = 0; i <= 10000; i++) {
panel.sleep(SLEEP_TIME);
drawAll(g);
}
}
To:
public static void startGame(DrawingPanel panel, Graphics g) {
for (int i = 0; i <= 1; i++) {
panel.sleep(SLEEP_TIME);
drawAll(g);
}
}
or
public static void startGame(DrawingPanel panel, Graphics g) {
panel.sleep(SLEEP_TIME);
drawAll(g);
}
2nd option: execute the drawShooter() method before the startGame() method or don't execute the startGame() at all.
startGame(panel, g); drawShooter(g, SHOOTER_COLOR);
To:
drawShooter(g, SHOOTER_COLOR);
startGame(panel, g);
or
drawShooter(g, SHOOTER_COLOR);
Didn't you ask this same question or something similar to it yesterday? And you're passing in the class name to g.setColor(Color) method and need to pass in the parameter which holds the object: g.setColor(C)
Your use of Graphics is not good, as you shouldn't use a Graphics obtained from a component via getGraphics(), but I'm guessing that it's because that's what your instructor told you to do. Same for use of a while (true) loop. Instead you should use a Swing Timer.
Like stated before g.setcolor(c) is required
check your error msgs since it allows you to gather that error and the shooterPosition error(its not public so cant be used inside a method)
I am writing a code of game bean machine(Galton box), its mechanism that one ball fall and move randomly until it get to one of the slots (randomly) and then another ball comes doing the same thing and so on, the problem is that all balls fall at the same time which something I do not want, I want each ball to fall when the current one finishes its travel..can anyone helps me ! Thanks..
here is the code:
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Random;
import java.util.Scanner;
import java.lang.Iterable;
import javax.swing.*;
public class BallPanel extends JPanel {
int x=1, y=1;
Collection <Ball> ball;
public static void main(String [] args){
// create the list
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame= new JFrame("Bean game");
frame.add(new BallPanel());
frame.setSize(300,500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
public BallPanel() {
JPanel panel = new JPanel();
ball=new ArrayList<>();
for(int i=1;i<=4;i++){
ball.add(new Ball(x,y));
x++;
y++;
}
Timer timer = new Timer(400, new ActionListener()
{
public void actionPerformed(ActionEvent e) {
for (Ball b: ball) {
b.move();repaint();
}
}
});
timer.start();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int raduis=10;
int i=0;
int width=(getWidth()/8);
int space=(getWidth()-8*30)/2;
g.setColor(Color.BLACK);
for(i=0;i<=8;i++){
g.drawLine(space+(30*i),getHeight()-5*(raduis) ,space+(30*i) ,getHeight() );
if(i!=0 && i!=8)
g.fillOval(space+(30*i)-5, getHeight()-5*(raduis)-5, 10, 10);
if(i==0){
g.drawLine(space,getHeight()-5*(raduis) , space+((8)*15)-(raduis/2)-15 , getHeight()-15-(5*raduis)-(30*(8-2))-raduis/2);
g.drawLine(space+((8)*15)-(raduis/2)-15 , getHeight()-15-(5*raduis)-(30*(8-2))-raduis/2 , space+((8)*15)-(raduis/2)-15 , getHeight()/2-8*8);//vertical line
}
if(i==8){
g.drawLine(space+(30*i), getHeight()-5*(raduis), space+((8)*15)+(raduis/2)+15, getHeight()-15-(5*raduis)-(30*(8-2))-raduis/2);
g.drawLine(space+((8)*15)+(raduis/2)+15 , getHeight()-15-(5*raduis)-(30*(8-2))-raduis/2 , space+((8)*15)+(raduis/2)+15 , getHeight()/2-8*8);//vertical line
}
}
int o=1;
for(i=1;i<=8-2;i++){
int k=2;
for(int j=i;j<=8-2;j++){
g.fillOval(space+((i+k)*15)-raduis/2, getHeight()-(5*raduis)-(30*o)-raduis/2, raduis, raduis);
k=k+2;
}o++;
}
for (Ball b : ball) {
b.draw(g);
}
}
public class Ball {
Random rand=new Random();
private int n;
private int raduis = 10;
private int moveRaduis=12;
private int L = 0;
private int R = 0;
private int D = 0;
int x, y;
public Ball(int x, int y){
this.x=x;
this.y=y;
}
public void draw(Graphics g) {
g.setColor(Color.RED);
g.fillOval(getWidth()/2 -raduis/2 + R + L, 0 + D , moveRaduis, moveRaduis);
}
public void move() {
n=1+rand.nextInt(100);
if(n<=51){
D+=15;
if(D<=(getHeight()-15-(5*raduis)-(30*(8-2))-raduis/2))
L=0;
else if(D>getHeight()-15-(5*raduis)-(30*(8-2))-raduis/2 && D<getHeight()-5*(raduis))
{
D+=15;
L-=15;
}
else if(D>=getHeight()-5*(raduis))
{
if(D==31*15)D-=15;
D=D;
}
}
else if (n>=51 && n<=100){
D+=15;
if(D<=getHeight()-15-(5*raduis)-(30*(8-2))-raduis/2)
R=0;
else if(D>getHeight()-15-(5*raduis)-(30*(8-2))-raduis/2 && D<getHeight()-5*(raduis))
{
D+=15;
R+=15;
}
else if(D>=getHeight()-5*(raduis)){
if(D==31*15)D-=15;
D=D;
}
}
}
}
}
So, your movement code moves all the balls on each iteration, what you need to do is have an "active" ball, for example...
private Ball activeBall;
Timer timer = new Timer(400, new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (activeBall != null && activeBall.hasCompleted()) {
activeBall = null;
}
if (activeBall == null && ball.size() > 0) {
activeBall = ball.remove(0);
}
if (activeBall != null) {
activeBall.move();
repaint();
}
}
});
You'll need to add in some kind of check to determine the ball has completed it's run though
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I created a GUI named Menu class for my Start, Help and Exit button. my problem is my game won't start, it hangs everytime I press the Start button. Can someone check my error and explain it to me because its my case study at school.
package spaceSip;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
public class Menu extends JFrame implements ActionListener
{
private JLabel titleL;
private JButton startB, helpB, exitB;
static JFrame frame1 = new JFrame();
public Menu()
{
frame1.setSize(500,250);
Container mainP = frame1.getContentPane();
mainP.setLayout(null);
titleL = new JLabel("WELCOME");
startB = new JButton("Start");
helpB = new JButton("Help");
exitB = new JButton("Exit");
mainP.add(titleL);
titleL.setFont(new Font("Chiller",Font.BOLD,50));
titleL.setBounds(100, 30, 200, 50);
mainP.add(startB);
startB.setMnemonic(KeyEvent.VK_S);
startB.setBounds(200, 80, 100, 20);
mainP.add(helpB);
helpB.setMnemonic(KeyEvent.VK_H);
helpB.setBounds(200, 100, 100, 20);
mainP.add(exitB);
exitB.setMnemonic(KeyEvent.VK_E);
exitB.setBounds(200, 120, 100, 20);
startB.addActionListener(this);
helpB.addActionListener(this);
exitB.addActionListener(this);
frame1.setVisible(true);
frame1.setResizable(false);
}
public void actionPerformed(ActionEvent e)
{
String key = e.getActionCommand();
if(key == "Start")
{
frame1.dispose();
new SpaceShipMain();
}
else if(key == "Help")
{
}
else
System.exit(0);
}
public static void main(String[]args)
{
new Menu();
}
}
package spaceSip;
import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class SpaceShipMain implements MouseListener
{
private JFrame background;
private SpaceShipPanel back;
public static boolean paused;
public static boolean crashed;
public static boolean started;
public static boolean playedOnce;
public boolean goingUp;
private double upCount;
public static int distance;
public static int maxDistance;
public final int XPOS;
public final int NUMRECS;
public final int RECHEIGHT;
public final int RECWIDTH;
private int moveIncrement;
private int numSmoke;
private ArrayList<SpaceShipImage> toprecs;
private ArrayList<SpaceShipImage> bottomrecs;
private ArrayList<SpaceShipImage> middlerecs;
private ArrayList<SpaceShipImage> smoke;
private SpaceShipImage helicopter;
public SpaceShipMain()
{
NUMRECS = 100;
RECHEIGHT = 70;
RECWIDTH = 30;
XPOS = 200;
playedOnce = false;
maxDistance = 0;
load(new File("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/Best.txt"));
initiate();
}
public void load(File file)
{
try
{
Scanner reader = new Scanner(file);
while(reader.hasNext())
{
int value = reader.nextInt();
if(value > maxDistance)
maxDistance = value;
}
}
catch(IOException i )
{
System.out.println("Error. "+i);
}
}
public void save()
{
FileWriter out;
try
{
out = new FileWriter("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/Best.txt");
out.write("" + maxDistance);
out.close();
}
catch(IOException i)
{
System.out.println("Error: "+i.getMessage());
}
}
public void initiate()
{
if(!playedOnce)
{
background = new JFrame("Space Ship Game");
background.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //closes the program when the window is closed
background.setResizable(false); //don't allow the user to resize the window
background.setSize(new Dimension(800,500));
background.setVisible(true);
back = new SpaceShipPanel("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/starfield.jpg");
background.add(back);
back.addMouseListener(this);
}
playedOnce = true;
goingUp = false;
paused = false;
crashed = false;
started = false;
distance = 0;
upCount = 0;
moveIncrement = 2;
numSmoke = 15;
toprecs = new ArrayList<SpaceShipImage>();
middlerecs = new ArrayList<SpaceShipImage>();
bottomrecs = new ArrayList<SpaceShipImage>();
smoke = new ArrayList<SpaceShipImage>();
helicopter = new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/rocketship.GIF",XPOS,200);
for(int x = 0; x < NUMRECS; x++)
toprecs.add(new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/rec2.JPG",RECWIDTH*x,5));
for(int x = 0; x < NUMRECS; x++)
bottomrecs.add(new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/rec2.JPG",RECWIDTH*x,410));
middlerecs.add(new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/asteroid2.jpg",1392,randomMidHeight()));
middlerecs.add(new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/asteroid2.jpg",1972,randomMidHeight()));
drawRectangles();
}
public void drawRectangles()
{
long last = System.currentTimeMillis();
long lastCopter = System.currentTimeMillis();
long lastSmoke = System.currentTimeMillis();
long lastSound = System.currentTimeMillis();
int firstUpdates = 0;
double lastDistance = (double)System.currentTimeMillis();
while(true)
{
if(!paused && !crashed && started && (double)System.currentTimeMillis() - (double)(2900/40) > lastDistance)
{
lastDistance = System.currentTimeMillis();
distance++;
}
if(!paused && !crashed && started && System.currentTimeMillis() - 10 > lastCopter)
{
lastCopter = System.currentTimeMillis();
updateCopter();
updateMiddle();
}
if(!paused && !crashed && started && System.currentTimeMillis() - 100 > last)
{
last = System.currentTimeMillis();
updateRecs();
}
if(!paused && !crashed && started && System.currentTimeMillis() - 75 > lastSmoke)
{
lastSmoke = System.currentTimeMillis();
if (firstUpdates < numSmoke)
{
firstUpdates++;
smoke.add(new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/smoke.GIF",187,helicopter.getY()));
for(int x = 0; x < firstUpdates; x++)
smoke.set(x,new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/smoke.GIF",smoke.get(x).getX() - 12, smoke.get(x).getY()));
}
else
{
for(int x = 0; x < numSmoke - 1; x++)
smoke.get(x).setY(smoke.get(x+1).getY());
smoke.set(numSmoke - 1,new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/smoke.GIF",187,helicopter.getY()));
}
}
back.updateImages(middlerecs,helicopter,smoke);
}
}
public void updateRecs()
{
for(int x = 0; x < (NUMRECS - 1); x++) //move all but the last rectangle 1 spot to the left
{
toprecs.set(x,new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/rec2.JPG",RECWIDTH*x,toprecs.get(x+1).getY()));
bottomrecs.set(x,new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/rec2.JPG",RECWIDTH*x,bottomrecs.get(x+1).getY()));
}
}
public void randomDrop()
{
toprecs.get(26).setY(toprecs.get(26).getY() + (463 - bottomrecs.get(26).getY()));
bottomrecs.get(26).setY(463);
}
public int randomMidHeight()
{
int max = 10000;
int min = 0;
for(int x = 0; x < NUMRECS; x++)
{
if(toprecs.get(x).getY() > min)
min = (int)toprecs.get(x).getY();
if(bottomrecs.get(x).getY() < max)
max = (int)bottomrecs.get(x).getY();
}
min += RECHEIGHT;
max -= (RECHEIGHT + min);
return min + (int)(Math.random() * max);
}
//moves the randomly generated middle rectangles
public void updateMiddle()
{
if(middlerecs.get(0).getX() > -1 * RECWIDTH)
{
middlerecs.set(0,new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/asteroid.gif",middlerecs.get(0).getX() - (RECWIDTH/5), middlerecs.get(0).getY()));
middlerecs.set(1,new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/asteroid.gif",middlerecs.get(1).getX() - (RECWIDTH/5), middlerecs.get(1).getY()));
}
else
{
middlerecs.set(0,new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/asteroid.gif",middlerecs.get(1).getX() - (RECWIDTH/5), middlerecs.get(1).getY()));
middlerecs.set(1,new SpaceShipImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/asteroid.gif",middlerecs.get(0).getX() + 580,randomMidHeight()));
}
}
public boolean shoot()
{
for(int x = 3; x <= 7; x++)
if(helicopter.getY() >= bottomrecs.get(x).getY())
return true;
for(int y = 3; y <= 7; y++)
if(helicopter.getY() <= toprecs.get(y).getY())
return true;
for(int z = 0; z <= 1; z++)
if(isInMidRange(z))
return true;
return false;
}
public boolean isInMidRange(int num)
{
Rectangle middlecheck = new Rectangle((int)middlerecs.get(num).getX(),(int)middlerecs.get(num).getY(),RECWIDTH,RECHEIGHT);
Rectangle coptercheck = new Rectangle((int)helicopter.getX(),(int)helicopter.getY(),70,48); //asteroid X and y bump
return middlecheck.intersects(coptercheck);
}
public void crash()
{
crashed = true;
if(distance > maxDistance)
{
maxDistance = distance;
save();
}
int reply = JOptionPane.showConfirmDialog(null, " RESTART ?", "GAME OVER", JOptionPane.YES_NO_OPTION);
if(reply == JOptionPane.YES_OPTION)
initiate();
else
System.exit(0);
initiate();
}
//moves the spaceship
public void updateCopter()
{
upCount += .10;
if(goingUp)
{
if(upCount < 3.5)
helicopter.setPosition(XPOS,(double)(helicopter.getY() - (.3 + upCount)));
else
helicopter.setPosition(XPOS,(double)(helicopter.getY() - (1.2 + upCount)));
helicopter.setImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/rocketship.GIF");
}
else
{
if(upCount < 1)
helicopter.setPosition(XPOS,(double)(helicopter.getY() + upCount));
else
helicopter.setPosition(XPOS,(double)(helicopter.getY() + (1.2 + upCount)));
helicopter.setImage("C:\\Users/Travelmate/workspace/GAME/src/spaceSip/rocketship.GIF");
}
if(shoot())
crash();
}
//Called when the mouse exits the game window
public void mouseExited(MouseEvent e)
{
paused = true;
}
//Called when the mouse enters the game window
public void mouseEntered(MouseEvent e)
{
}
//Called when the mouse is released
public void mouseReleased(MouseEvent e)
{
goingUp = false;
upCount = -1;
if(paused)
paused = false;
}
//Called when the mouse is pressed
public void mousePressed(MouseEvent e)
{
if (!started)
started = true;
goingUp = true;
upCount = 0;
}
//Called when the mouse is released
public void mouseClicked(MouseEvent e)
{
}
}
package spaceSip;
import java.awt.Image;
import javax.swing.ImageIcon;
public class SpaceShipImage
{
private Image image; //The picture
private double x; //X position
private double y; //Y position
//Construct a new Moving Image with image, x position, and y position given
public SpaceShipImage(Image img, double xPos, double yPos)
{
image = img;
x = xPos;
y = yPos;
}
//Construct a new Moving Image with image (from file path), x position, and y position given
public SpaceShipImage(String path, double xPos, double yPos)
{
this(new ImageIcon(path).getImage(), xPos, yPos);
//easiest way to make an image from a file path in Swing
}
//They are set methods. I don't feel like commenting them.
public void setPosition(double xPos, double yPos)
{
x = xPos;
y = yPos;
}
public void setImage(String path)
{
image = new ImageIcon(path).getImage();
}
public void setY(double newY)
{
y = newY;
}
public void setX(double newX)
{
x = newX;
}
//Get methods which I'm also not commenting
public double getX()
{
return x;
}
public double getY()
{
return y;
}
public Image getImage()
{
return image;
}
}
package spaceSip;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Image;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
class SpaceShipPanel extends JPanel
{
private Image background;
private ArrayList<SpaceShipImage> middle;
private SpaceShipImage copter;
private ArrayList<SpaceShipImage> smoke;
//Constructs a new ImagePanel with the background image specified by the file path given
public SpaceShipPanel(String img)
{
this(new ImageIcon(img).getImage());
//The easiest way to make images from file paths in Swing
}
//Constructs a new ImagePanel with the background image given
public SpaceShipPanel(Image img)
{
background = img;
Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
//Get the size of the image
//Thoroughly make the size of the panel equal to the size of the image
//(Various layout managers will try to mess with the size of things to fit everything)
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
setSize(size);
middle = new ArrayList<SpaceShipImage>();
smoke = new ArrayList<SpaceShipImage>();
}
//This is called whenever the computer decides to repaint the window
//It's a method in JPanel that I've overwritten to paint the background and foreground images
public void paintComponent(Graphics g)
{
//Paint the background with its upper left corner at the upper left corner of the panel
g.drawImage(background, 0, 0, null);
//Paint each image in the foreground where it should go
for(SpaceShipImage img : middle)
g.drawImage(img.getImage(), (int)(img.getX()), (int)(img.getY()), null);
for(SpaceShipImage img : smoke)
g.drawImage(img.getImage(), (int)(img.getX()), (int)(img.getY()), null);
if(copter != null)
g.drawImage(copter.getImage(), (int)(copter.getX()), (int)(copter.getY()), null);
drawStrings(g);
}
public void drawStrings(Graphics g)
{
g.setColor(Color.WHITE);
g.setFont(new Font("Arial",Font.BOLD,20));
g.drawString("Distance: " + SpaceShipMain.distance,30,440);
g.setFont(new Font("Arial",Font.BOLD,20));
if (SpaceShipMain.distance > SpaceShipMain.maxDistance)
g.drawString("Best: " + SpaceShipMain.distance,650,440);
else
g.drawString("Best: " + SpaceShipMain.maxDistance,650,440);
if(SpaceShipMain.paused)
{
g.setFont(new Font("Chiller",Font.BOLD,72));
g.drawString("Paused",325,290);
g.setFont(new Font("Chiller",Font.BOLD,30));
g.drawString("Click to unpause.",320,340);
}
}
//Replaces the list of foreground images with the one given, and repaints the panel
public void updateImages(ArrayList<SpaceShipImage> newMiddle,SpaceShipImage newCopter,ArrayList<SpaceShipImage> newSmoke)
{
copter = newCopter;
middle = newMiddle;
smoke = newSmoke;
repaint(); //This repaints stuff... you don't need to know how it works
}
}
You compare Strings with equals(value equality) not with ==(reference equality). For more information read this previous question How do I compare strings in Java?
As #AndrewThompson always advice don't use NullLayout
Java GUIs might have to work on a number of platforms, on different
screen resolutions & using different PLAFs. As such they are not
conducive to exact placement of components. To organize the
components for a robust GUI, instead use layout managers, or
combinations of
them1, along
with layout padding & borders for white
space2.
As you say that your gui is blocked, that may be cause some of your execution code takes too more time and it's executed in the same thread as gui stuff (The Event Dispatch Thread). As you have a while(true) that's block the gui so use a SwingTimer for execute repeatidly task or if that code that takes long time execute it in a background thread using a Swing Worker. Here you have a complete example. When you perform custom painting you should override paintComponent and in first line you have to call super.paintComponent(..) to follow correct chaining. Read more in Painting in AWT-Swing.
Another error i see is that you are adding components after calling setVisible(true) without calling revalidate() repaint(). So i recommend to first add components to container then call setVisible(true) at final step.
I am having a problem getting my application to draw a Ball when i click on the frame.
I thought my code was correct, and I don't get any errors, but it still doesn't work.
I feel the problem is with the MouseListener implementation and that the application is not handling the MouseEvent properly.
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class BouncingBallApp extends JFrame
{
public static void main(String[] args)
{
Container container;
BouncingBallApp bouncingBalls = new BouncingBallApp();
bouncingBalls.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
container = new Container();
BouncingBallPanel BBP = new BouncingBallPanel();
container.add(BBP);
bouncingBalls.addMouseListener(BBP);
//addMouseListener;
bouncingBalls.setBackground( Color.WHITE );
bouncingBalls.setSize(400,300);
bouncingBalls.setVisible( true );
}//end of main method
}//end of BouncingBallApp
class BouncingBallPanel extends JPanel implements MouseListener, Runnable
{
private Ball[] ballArray = new Ball[20];
private int ballCount = 0;
public void run()
{
for(int i = 0; i<ballArray.length; i++){
if(ballArray[i] != null){
ballArray[i].move();}}
repaint();
//delay(1);
}
public void mouseClicked(MouseEvent e)
{
ballArray[ballCount] = new Ball();
ballCount++;
if(ballCount == 1)
(new Thread(new BouncingBallPanel())).start();
}
//empty interface methods
public void mouseExited(MouseEvent e){}
public void mouseReleased(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mousePressed(MouseEvent e){}
public void paintComponent(Graphics g)
{
super.paintComponent( g );
Graphics2D g2d = (Graphics2D) g;
for(int i = 0; i<ballArray.length; i++)
{
if(ballArray[i] != null){
g2d.setColor(ballArray[i].getColor());
g2d.fill(new Ellipse2D.Double(ballArray[i].getX(),ballArray[i].getY(),ballArray
[i].getDiameter(),ballArray[i].getDiameter()));}
}//end of for loop
}
}//end of BouncingBallPanel
class Ball
{
private double x;
private double y;
private double deltaX;
private double deltaY;
private double diameter;
private Color color;
Random random = new Random();
public Ball()
{
x = random.nextInt(400);
y = random.nextInt(300);
deltaX = 2;
deltaY = 2;
diameter = 10;
color = new Color(random.nextInt(256),random.nextInt(256),random.nextInt(256));
}//end of constructor
public double getX(){
return x;}
public double getY(){
return y;}
public double getDiameter(){
return diameter;}
public Color getColor(){
return color;}
public void move()
{
x += deltaX;
y += deltaY;
if (x < 0) {
x = 0;
deltaX = -deltaX;}
else if (x > 400) {
x = 400;
deltaX = -deltaX;}
if (y < 0) {
y = 0;
deltaY = -deltaY;}
else if (y > 300) {
y = 300;
deltaY = -deltaY;}
}//end of method move
}//end of ball
3 Things
No size for container
You are not adding container
No loop to update graphics
The code below is working
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class BouncingBallApp extends JFrame {
public static void main(String[] args) {
// Container container;
BouncingBallApp bouncingBalls = new BouncingBallApp();
bouncingBalls.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// container = new Container();
BouncingBallPanel BBP = new BouncingBallPanel();
// container.add(BBP);
bouncingBalls.addMouseListener(BBP);
// addMouseListener;
bouncingBalls.setBackground(Color.WHITE);
bouncingBalls.setSize(400, 300);
BBP.setSize(400, 300);
BBP.setLayout(null);
bouncingBalls.setContentPane(BBP);
/*
* JTextField jtf = new JTextField(); BBP.add(jtf); jtf.setSize(100,
* 20);
*/
bouncingBalls.setVisible(true);
}// end of main method
}// end of BouncingBallApp
class BouncingBallPanel extends JPanel implements MouseListener {
private Ball[] ballArray = new Ball[20];
private int ballCount = 0;
public void mouseClicked(MouseEvent e) {
ballArray[ballCount] = new Ball();
ballCount++;
if (ballCount == 1) {
final Runnable updateGraphics = new Runnable() {
public void run() {
for (int i = 0; i < ballArray.length; i++) {
if (ballArray[i] != null) {
ballArray[i].move();
}
}
repaint();
}
};
Runnable animation = new Runnable() {
public void run() {
while (true) {
try {
EventQueue.invokeLater(updateGraphics);
Thread.sleep(100);
} catch (InterruptedException e) {
return;
}
}
}
};
new Thread(animation).start();
}
}
// empty interface methods
public void mouseExited(MouseEvent e) {
}
public void mouseReleased(MouseEvent e) {
}
public void mouseEntered(MouseEvent e) {
}
public void mousePressed(MouseEvent e) {
}
public void paintComponent(Graphics g) {
// super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
for (int i = 0; i < ballArray.length; i++) { if (ballArray[i] !=
null) { System.out.println(" ball " + i + " , " +
ballArray[i].getColor() + " , " + ballArray[i].getX() + " , " +
ballArray[i].getY() + " , " + ballArray[i].getDiameter());
g2d.setColor(ballArray[i].getColor());
g2d.fillRect((int)ballArray[i].getX(), (int)ballArray[i].getY(),
(int)ballArray[i].getDiameter(), (int)ballArray[i].getDiameter()); }
}// end of for loop
}
}// end of BouncingBallPanel
class Ball {
private double x;
private double y;
private double deltaX;
private double deltaY;
private double diameter;
private Color color;
Random random = new Random();
public Ball() {
x = random.nextInt(400);
y = random.nextInt(300);
deltaX = 2;
deltaY = 2;
diameter = 10;
color = new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256));
}// end of constructor
public double getX() {
return x;
}
public double getY() {
return y;
}
public double getDiameter() {
return diameter;
}
public Color getColor() {
return color;
}
public void move() {
x += deltaX;
y += deltaY;
if (x < 0) {
x = 0;
deltaX = -deltaX;
}
else if (x > 400) {
x = 400;
deltaX = -deltaX;
}
if (y < 0) {
y = 0;
deltaY = -deltaY;
}
else if (y > 300) {
y = 300;
deltaY = -deltaY;
}
}// end of method move
}// end of ball