Hello Members,
I have a program (from Deitel Java Solution Manual) which bounces a ball using a Java thread inside a JPanel(which is inside a JFrame). When I made a custom class for the ball, the program is not painting anything on the JPanel.I would appreciate any help.
Following are my programs:
Ball.java:
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
import java.lang.Thread;
public class Ball extends JPanel implements Runnable
{
private boolean xUp, yUp, xUp1, yUp1;
private int x, y, xDx, yDy;
private final int MAX_X = 500, MAX_Y = 500;
private boolean flag = true;
private String color;
private Thread ball;
public Ball(int xCoordinate, int yCoordinate, String color)
{
x = xCoordinate;
y = yCoordinate;
color = color;
xUp = false;
yUp = false;
xDx = 1;
yDy = 1;
ball = new Thread(this);
ball.start();
}
public void paintBall( Graphics g )
{
super.paintComponent( g );
g.setColor( Color.red );
g.fillOval( x, y, 50, 50 );
}
public void run()
{
while ( flag == true )
{
try
{
ball.sleep(10);
}
catch ( InterruptedException exception )
{
System.err.println( exception.toString() );
}
if ( y <= 0 ) {
yUp = true;
yDy = ( int ) ( Math.random() * 5 + 2 );
}
else if ( y >= MAX_Y - 50 ) {
yDy = ( int ) ( Math.random() * 5 + 2 );
yUp = false;
}
if ( x <= 0 ) {
xUp = true;
xDx = ( int ) ( Math.random() * 5 + 2 );
}
else if ( x >= MAX_X - 50 ) {
xUp = false;
xDx = ( int ) ( Math.random() * 5 + 2 );
}
if ( xUp == true )
x += xDx;
else
x -= xDx;
if ( yUp == true )
y += yDy;
else
y -= yDy;
repaint();
}
}
}
The Java Frame:
//Source: Java Textbook (Deitel and Deitel) - Seventh Edition – Solution Manual, Chapter 16, Problem #23.8, Page 1118
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.lang.Thread;
public class Ball_Bounce extends JFrame
{
private Thread blueBall, redBall;
private boolean xUp, yUp, xUp1, yUp1;
private int x, y, xDx, yDy;
private final int MAX_X = 500, MAX_Y = 500;
private boolean flag = true;
private Ball ball;
public Ball_Bounce()
{
createBall();
add (ball);
setSize (500,500);
setVisible(true);
}
public void createBall()
{
ball = new Ball( 300, 250, "red" );
}
public static void main (String args [])
{
new Ball_Bounce();
}
}