Here is the entirety of my program. The problem is in the ballroll method, getting the red dot/ ball to move straight down the screen on the y-axis to reach the inner blue circle for a "ripple effect" illusion. Please help me do this. I changed the code from the ball moving along the x axis, it needs to move vertically only. Thank you in advance for your help.
import java.awt.Color;
import java.awt.Graphics;
public class Animation {
public static void main(String [] args) {
DrawingPanel panel = new DrawingPanel(350, 350);
Graphics g = panel.getGraphics();
background(g);
ballroll(panel, g);
drawCircles(g);
sunrayspotlight(g);
}
public static void background(Graphics g) {
g.setColor(Color.BLUE);
g.fillRect(0, 175, 350, 175);
g.setColor(Color.ORANGE);
g.fillRect(0, 0, 350, 175);
}
public static void sunrayspotlight(Graphics g) {
int radius = 5;
int x = 0;
while(x <= 100) {
g.setColor(Color.YELLOW);
g.fillOval(0, 0, radius, radius);
try {
Thread.sleep(5);
} catch (InterruptedException e) {
}
x++;
radius = radius + 5;
}
}
public static void drawCircles(Graphics g) {
int radius = 5;
int x = 0;
while(x <= 25) {
g.setColor(Color.CYAN);
int z = radius / 2;
g.drawOval(245 - z, 245 - z, radius, radius);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
x++;
radius = radius + 5;
}
}
private static void ballroll(DrawingPanel panel, Graphics g) {
//draw and roll the ball now
g.setColor(Color.RED);
int x = 115, y = 110, direction=1;
while(y<175){
g.fillOval(235, 0, 20, 20);
if (x==0){
y+=60;
direction *= -1;
}
else if (x < 115){
direction *= -1;
y+=60;
}
y+=direction*15;
System.out.println(x);
panel.sleep(80);
}
panel.sleep(800);
}
}
Related
Using Java graphics, I tried to draw a circle, draw lines inside it, then check if the mouse is inside the circle and print the position of the mouse.
The lines I draw exceed the circle and when I click inside the borders of these lines, but outside the circle, it assumes the mouse is inside the circle since the limits I gave to x and y actually form a square.
this is how my circle looks like
How can I find limits for x and y such that the lines won't exceed the circle and it will print "inside" only when the mouse is inside the circle?
this is how it should actually look like
Here is my code
public class Circle extends JFrame implements MouseListener {
int x,y,i;
JLabel label =new JLabel();
public void SetLayout(int x, int y, int w, int l, Component c){
c.setLocation(x, y);
c.setSize(w, l);
}
public Circle()
{
Container con = getContentPane();
setLayout(null);
SetLayout(10, 10, 70, 20, label);
con.add(label);
this.setSize(1000,500);
this.setResizable(false);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
addMouseListener(this);
}
public void paint(Graphics g)
{
super.paint(g);
g.setColor(Color.WHITE);
g.fillRect(0, 0, 1000, 1000);
g.setColor(Color.BLACK);
g.drawOval(300,50,400,400);
g.setColor(Color.cyan);
for (i = 2 ; i < 400 ; i += 5){
g.drawLine(300+i, 50 , 300+i, 450);
}
g.setColor(Color.BLACK);
label.setText( ((double)x-500)/100+" "+((double)y-250)/-100 );
g.drawLine(0, 250, 1000, 250);
g.drawLine(500, 0, 500, 500);
g.drawString("(0,0)",501,265);
g.drawString("1",601,265);
g.drawString("-1",401,265);
g.drawString("2",701,265);
g.drawString("-2",301,265);
g.drawString("3",801,265);
g.drawString("-3",201,265);
g.drawString("1",503,165);
g.drawString("-1",503,365);
g.drawString("2",503,65);
g.drawString("-2",503,465);
}
#Override
public void mouseClicked (MouseEvent e) {
x = e.getX();
y = e.getY();
if ((y >= 50 && y <= 450 && x >= 300) & x <= 700){
JOptionPane.showMessageDialog(null, "Inside");
}
else{
JOptionPane.showMessageDialog(null, "Outside");
}
repaint();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
new Circle();
}
#Override
public void mouseEntered(MouseEvent arg0) {
}
#Override
public void mouseExited(MouseEvent arg0) {
}
#Override
public void mousePressed(MouseEvent arg0) {
}
#Override
public void mouseReleased(MouseEvent arg0){
}
}
Maybe there can be a solution like calculating the clicked point's distance from the center and check if the distance is smaller than the radius. But still, this wouldn't solve the exceeding lines problem.
With Trigonometry:
By using the inverse cosine function you can get the angle between the x-axis and the point on the circle for that x coordinate. Then by plugging that angle into the sin function you can get the y position of that point on the circle.
Point circleCenter;
int radius;
int lineDistance;
for (int x = -radius; x < radius; x += lineDistance) {
float double = Math.acos(x / radius);
int y = Math.sin(angle) * radius;
int top = circleCenter.y + y;
int bottom = circleCenter.y - y;
g.drawLine(x + circleCenter.x, top, x + circleCenter.y, bottom);
}
If you have time, how about recearching about trigonometry
https://www.mathsisfun.com/algebra/trigonometry.html
it really is a fascinating subject and essential for any programmer.
Checking if the mouse is inside the circle:
Point mousePosition;
Point circleCenter;
int radius;
Point centerToMouse = new Point(mousePosition.x - circleCenter.x, mousePosition.y - circleCenter.y);
bool mouseInside = (int)Math.sqrt(centerToMouse.x * centerToMouse.x + centerToMouse.y * centerToMouse.y) <= radius;
Im trying to display the maximum number of smaller rectangles that will fit into a larger one. I can get the horizontal rectangles to show up, but the vertical rectangles will not show up. I need help on figuring out how to get the vertical rectangles to display in the JFrame.
Here is the class with the main:
import javax.swing.*;
public class MyPanel extends JComponent {
public static void main(String[] arguments) {
LargeRec large = new LargeRec();
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame = new JFrame("Rectangle");
frame.setResizable(false);
frame.setVisible(true);
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setSize(500,400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(large);
}
}
This is the class for creating the rectangle's:
import javax.swing.*;
import java.awt.*;
public class LargeRec extends JComponent {
static int larX;
static int larY;
static int smaX;
static int smaY;
public static int getRandomIntRange(int min, int max) {
int x = (int) (Math.random() * ((max + 1 - min))) + min;
if (x > (max + 1))
x = max;
return x;
}
public void paint(Graphics g) {
larX = getRandomIntRange(100, 300);
larY = getRandomIntRange(100, 300);
while (larX == larY) {
larX = getRandomIntRange(100, 300);
larY = getRandomIntRange(100, 300);
}
while (larY > larX) {
larX = getRandomIntRange(100, 300);
larY = getRandomIntRange(100, 300);
}
smaX = getRandomIntRange(10, 50);
smaY = getRandomIntRange(10, 50);
while (smaX == smaY) {
smaX = getRandomIntRange(10, 50);
smaY = getRandomIntRange(10, 50);
}
while (smaY > smaX) {
smaX = getRandomIntRange(10, 50);
smaY = getRandomIntRange(10, 50);
}
g.drawRect(0, 0, larX, larY);
g.setColor(Color.black);
g.fillRect(0, 0, larX, larY);
int LX = larX;
int LY = larY;
int SX = smaX;
int SY = smaY;
for (int nx = 0; nx <= larX; nx = nx + smaX) {
while (LY >= SY) {
LY = LY - SY;
if(LX>=SX) {
g.setColor(Color.red);
g.drawRect(nx, LY, smaX, smaY);
}
}
LX = LX - SX;
LY = larY;
}
Graphics2D g2 = (Graphics2D) g;
for (int ny =LX; ny+smaY <=LX ; ny = ny + smaY) {
while (LY >= SX) {
g2.setColor(Color.blue);
g2.drawRect(ny, LY, smaY, smaX);
LY = LY - SX;
}
LY=larY;
}
}
}
It should output a black rectangle with smaller horizontal rectangles and vertical rectangles. It displays the horizontal (red) rectangles, but not the vertical(blue) rectangles.
Here is an example of a bad output:
I have a problem.
I am a beginner with java, and succeeded up to this point. Add bubbles with random sizes.
Now I need to make the bubbles escaping mouse when he gets near them.
Can anyone give me a hint how?
Thank you.
public class BounceBall extends JFrame {
private ShapePanel drawPanel;
private Vector<NewBall> Balls;
private JTextField message;
// set up interface
public BounceBall() {
super("MultiThreading");
drawPanel = new ShapePanel(400, 345);
message = new JTextField();
message.setEditable(false);
Balls = new Vector<NewBall>();
add(drawPanel, BorderLayout.NORTH);
add(message, BorderLayout.SOUTH);
setSize(400, 400);
setVisible(true);
}
public static void main(String args[]) {
BounceBall application = new BounceBall();
application.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
private class NewBall extends Thread {
private Ellipse2D.Double thisBall;
private boolean ballStarted;
private int size, speed; // characteristics
private int deltax, deltay; // of the ball
public NewBall() {
ballStarted = true;
size = 10 + (int) (Math.random() * 60);
speed = 10 + (int) (Math.random() * 100);
int startx = (int) (Math.random() * 300);
int starty = (int) (Math.random() * 300);
deltax = -10 + (int) (Math.random() * 21);
deltay = -10 + (int) (Math.random() * 21);
if ((deltax == 0) && (deltay == 0)) {
deltax = 1;
}
thisBall = new Ellipse2D.Double(startx, starty, size, size);
}
public void draw(Graphics2D g2d) {
if (thisBall != null) {
g2d.setColor(Color.BLUE);
g2d.fill(thisBall);
}
}
public void run() {
while (ballStarted) // Keeps ball moving
{
try {
Thread.sleep(speed);
} catch (InterruptedException e) {
System.out.println("Woke up prematurely");
}
// calculate new position and move ball
int oldx = (int) thisBall.getX();
int oldy = (int) thisBall.getY();
int newx = oldx + deltax;
if (newx + size > drawPanel.getWidth() || newx < 0) {
deltax = -deltax;
}
int newy = oldy + deltay;
if (newy + size > drawPanel.getHeight() || newy < 0) {
deltay = -deltay;
}
thisBall.setFrame(newx, newy, size, size);
drawPanel.repaint();
}
}
}
private class ShapePanel extends JPanel {
private int prefwid, prefht;
public ShapePanel(int pwid, int pht) {
prefwid = pwid;
prefht = pht;
// add ball when mouse is clicked
addMouseListener(
new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
NewBall nextBall = new NewBall();
Balls.addElement(nextBall);
nextBall.start();
message.setText("Number of Balls: " + Balls.size());
}
});
}
public Dimension getPreferredSize() {
return new Dimension(prefwid, prefht);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
for (int i = 0; i < Balls.size(); i++) {
(Balls.elementAt(i)).draw(g2d);
}
}
}
}
You should not have a Thread for each individual ball, this will not scale well, the more balls you add, the more threads you add. At some point, the amount of work it takes to manage the threads will exceed the benefit for using multiple threads...
Also, I doubt if your need 1000fps...something like 25fps should be more than sufficient for your simple purposes. This will give the system some breathing room and allow other threads within the system time to execute.
Lets start with a simple concept of a Ball. The Ball knows where it is and which direction it is moving it, it also knows how to paint itself, for example...
public class Ball {
private int x;
private int y;
private int deltaX;
private int deltaY;
private int dimeter;
private Ellipse2D ball;
private Color color;
public Ball(Color color, Dimension bounds) {
this.color = color;
Random rnd = new Random();
dimeter = 5 + rnd.nextInt(15);
x = rnd.nextInt(bounds.width - dimeter);
y = rnd.nextInt(bounds.height - dimeter);
if (x < 0) {
x = 0;
}
if (y < 0) {
y = 0;
}
int maxSpeed = 10;
do {
deltaX = rnd.nextInt(maxSpeed) - (maxSpeed / 2);
} while (deltaX == 0);
do {
deltaY = rnd.nextInt(maxSpeed) - (maxSpeed / 2);
} while (deltaY == 0);
ball = new Ellipse2D.Float(0, 0, dimeter, dimeter);
}
public void update(Dimension bounds) {
x += deltaX;
y += deltaY;
if (x < 0) {
x = 0;
deltaX *= -1;
} else if (x + dimeter > bounds.width) {
x = bounds.width - dimeter;
deltaX *= -1;
}
if (y < 0) {
y = 0;
deltaY *= -1;
} else if (y + dimeter > bounds.height) {
y = bounds.height - dimeter;
deltaY *= -1;
}
}
public void paint(Graphics2D g2d) {
g2d.translate(x, y);
g2d.setColor(color);
g2d.fill(ball);
g2d.translate(-x, -y);
}
}
Next, we need somewhere for the balls to move within, some kind of BallPit for example...
public class BallPit extends JPanel {
private List<Ball> balls;
public BallPit() {
balls = new ArrayList<>(25);
balls.add(new Ball(Color.RED, getPreferredSize()));
Timer timer = new Timer(40, new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
for (Ball ball : balls) {
ball.update(getSize());
}
repaint();
}
});
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(200, 200);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
for (Ball ball : balls) {
ball.paint(g2d);
}
g2d.dispose();
}
}
This maintains a list of balls, tells them when the need to update and when the need to paint. This example uses a simple javax.swing.Timer, which acts as the central timer which updates the balls and schedules the repaints.
The reason for this is takes care of synchronisation between the updates and the paints, meaning that the balls won't be updating while they are been painted. This is achieved because javax.swing.Timer triggers it's callbacks within the context of the EDT.
See Concurrency in Swing and How to use Swing Timers for more details.
Okay, so that fixes the threading issues, but what about the mouse avoidance...
That's a little more complicated...
What we need to is add a MouseMoitionListener to the BillPit and record the last position of the mouse.
public class BallPit extends JPanel {
//...
private Point mousePoint;
//...
public BallPit() {
//...
MouseAdapter handler = new MouseAdapter() {
#Override
public void mouseMoved(MouseEvent e) {
mousePoint = e.getPoint();
}
#Override
public void mouseExited(MouseEvent e) {
mousePoint = null;
}
};
addMouseListener(handler);
addMouseMotionListener(handler);
//...
The reason for including mouseExit is to ensure that balls don't try and move away from a phantom mouse cursor...
Next, we need to update Ball to have an "area of effect", this is the area around the ball that will trigger a change in movement if the mouse cursor moves within it's range...
public class Ball {
//...
private final Ellipse2D.Float areaOfEffect;
public Ball(Color color, Dimension bounds) {
//...
areaOfEffect = new Ellipse2D.Float(-10, -10, dimeter + 20, dimeter + 20);
}
Now, I also add some additional painting for debug reasons...
public void paint(Graphics2D g2d) {
g2d.translate(x, y);
g2d.setColor(new Color(0, 0, 192, 32));
g2d.fill(areaOfEffect);
g2d.setColor(color);
g2d.fill(ball);
g2d.translate(-x, -y);
}
Next, we need to modify the Ball's update method to accept the mousePoint value...
public void update(Dimension bounds, Point mousePoint) {
PathIterator pathIterator = areaOfEffect.getPathIterator(AffineTransform.getTranslateInstance(x, y));
GeneralPath path = new GeneralPath();
path.append(pathIterator, true);
if (mousePoint != null && path.contains(mousePoint)) {
// Determine which axis is closes to the cursor...
int xDistance = Math.abs(x + (dimeter / 2) - mousePoint.x);
int yDistance = Math.abs(y + (dimeter / 2) - mousePoint.y);
if (xDistance < yDistance) {
// If x is closer, the change the delatX
if (x + (dimeter / 2) < mousePoint.x) {
if (deltaX > 0) {
deltaX *= -1;
}
} else {
if (deltaX > 0) {
deltaX *= -1;
}
}
} else {
// If y is closer, the change the deltaY
if (y + (dimeter / 2) < mousePoint.y) {
if (deltaY > 0) {
deltaY *= -1;
}
} else {
if (deltaY > 0) {
deltaY *= -1;
}
}
}
}
//...Rest of previous method code...
}
Basically, what this is trying to do is determine which axis is closer to the mouse point and in which direction the ball should try and move...it's a little "basic", but gives the basic premise...
Lastly, we need to update the "update" loop in the javax.swing.Timer to supply the additional parameter
for (Ball ball : balls) {
ball.update(getSize(), mousePoint);
}
I'm going to answer this, but I'm very close to issuing a close vote because it doesn't show what you've done so far to attempt this. I would not be surprised if others are closer to the edge than I am on this. At the same time, you've clearly shown your progress before you reached this point, so I'll give you the benefit of the doubt. In the future, I would strongly advise making an attempt and then posting a question that pertains to the specific problem you're having while making that attempt.
You need two things:
The current location of the mouse
A range check and reversal of direction if too close.
The location of the mouse can be achieved by adding two variables (x and y) and, every time the mouse is moved (so add a mouse event listener to your JPanel or something) update those variables with the new location.
Then, you can do a range check (think Pythagorean theorem) on each bubble to make sure they're far enough away. If the bubble is too close, you'll want to check where that bubble would end up if it carried on its current course, as well as where it would end up if it changed X direction, Y direction, or both. Pick the one that ends up being furthest away and set the deltax and deltay to those, and let the calculation carry on as normal.
It sounds like a lot, but those are the two basic components you need to achieve this.
I'm tyring to link to circles with drawline , but I have a problem here is my code :
import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics;
import javax.swing.JPanel;
public class Panneau extends JPanel {
public void paintComponent(Graphics g){
// declaration
String text = "test";
int x = 250, y = 200;
int height = 50, width = 50;
g.setColor(Color.yellow);
g.fillOval(x-height/2, y-width/2,width, height);
g.fillOval((x-height/2)+100, (y-width/2)+50,width, height);
FontMetrics fm = g.getFontMetrics();
double textWidth = fm.getStringBounds(text, g).getWidth();
g.setColor(Color.black);
g.drawString(text, (int) (x - textWidth/2),(int) (y + fm.getMaxAscent() / 2));
g.drawString(text, (int) (x - textWidth/2)+100,(int) (y + fm.getMaxAscent() / 2)+50);
g.setColor(Color.black);
g.drawLine(x,y,x+100,y+50);
}
}
the problem , the line I drawed start from center of circle , I want to draw Line from circle (like Graph node!) thanks for helping ! :)
Actually, I realized there was a way to 'hack it' by drawing the graphic elements in a different order. This still draws the entire line, but then effectively 'erases the unwanted bits' by ..drawing over the top of them!
import java.awt.*;
import javax.swing.*;
public class Panneau extends JPanel {
public void paintComponent(Graphics g){
// declaration
String text = "test";
int x = 250, y = 200;
int height = 50, width = 50;
g.setColor(Color.black);
g.drawLine(x,y,x+100,y+50);
g.setColor(Color.yellow);
g.fillOval(x-height/2, y-width/2,width, height);
g.fillOval((x-height/2)+100, (y-width/2)+50,width, height);
FontMetrics fm = g.getFontMetrics();
double textWidth = fm.getStringBounds(text, g).getWidth();
g.setColor(Color.black);
g.drawString(text, (int) (x - textWidth/2),(int) (y + fm.getMaxAscent() / 2));
g.drawString(text, (int) (x - textWidth/2)+100,(int) (y + fm.getMaxAscent() / 2)+50);
}
public Dimension getPreferredSize() {
return new Dimension(400,280);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
public void run() {
Panneau p = new Panneau();
JOptionPane.showMessageDialog(null, p);
}
};
SwingUtilities.invokeLater(r);
}
}
sorry to keep asking questions about my program but i think i'm nearly there and i'm teaching myself java so please bear with me. I'm creating an applet that moves sheep object across the screen in a random direction when a dog object moves close to the sheep. Getting the sheep to move in a random direction took some work and with the help of you guys on here it now works (sort of) but what I'm trying to do now is stop it from flickering when i drag objects across the screen. I've read about double buffering, I can get it to work for items drawn in the paint method of a main class but cant get it to work for my sheep and dog objects which are defined as separate objects in separate classes. Any help will be much appreciated. Here is my code:
package mandAndDog;
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
public class SheepDog extends Applet implements ActionListener, MouseListener, MouseMotionListener
{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
*
*/
Dog dog;
Sheep sheep;
int[] directionNumbersLeft = {0, 1, 3};
int[] directionNumbersUp = {0, 1, 2};
int x;
int selection;
int xposR;
int yposR;
int sheepx;
int sheepy;
int sheepBoundsx;
int sheepBoundsy;
int MAX_DISTANCE = 50;
int direction;
int distance;
Boolean sheepisclosetodog;
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
dog = new Dog(10, 10);
sheepx = 175;
sheepy = 75;
sheep = new Sheep(sheepx, sheepy);
sheepBoundsx = 30;
sheepBoundsy = 30;
direction = (int)(Math.random()*4);
distance = (int) (Math.random() * MAX_DISTANCE) % MAX_DISTANCE;
sheepisclosetodog = false;
Random rand = new Random();
x = rand.nextInt(3);
selection = directionNumbersLeft[x];
}
public void paint(Graphics g)
{
dog.display(g);
sheep.display(g);
g.drawString(Integer.toString(distance), 85, 100);
g.drawString(Integer.toString(direction), 85, 125);
g.drawString(Integer.toString(selection), 85, 140);
}
public void actionPerformed(ActionEvent ev)
{}
public void mousePressed(MouseEvent e)
{}
public void mouseReleased(MouseEvent e)
{}
public void mouseEntered(MouseEvent e)
{}
public void mouseExited(MouseEvent e)
{}
public void mouseMoved(MouseEvent e)
{
}
public void mouseClicked(MouseEvent e)
{}
public void mouseDragged(MouseEvent e)
{
dog.setLocation(xposR, yposR);
sheep.setLocation(sheepx, sheepy);
if (xposR > (sheepx - 20)&& xposR < (sheepx - 20)+(sheepBoundsx - 20) && yposR > (sheepy - 20)
&& yposR < (sheepy - 20)+(sheepBoundsy - 20) && direction == 0){
sheepx = sheepx + 50;
direction = (int)(Math.random()*4);
}
if (xposR > (sheepx - 20)&& xposR < (sheepx - 20)+(sheepBoundsx - 20) && yposR > (sheepy - 20)
&& yposR < (sheepy - 20)+(sheepBoundsy - 20) && direction == 1){
sheepy = sheepy + 50;
direction = (int)(Math.random()*4);
}
if (xposR > (sheepx - 20)&& xposR < (sheepx - 20)+(sheepBoundsx - 20) && yposR > (sheepy - 20)
&& yposR < (sheepy - 20)+(sheepBoundsy - 20) && direction == 2){
sheepx = sheepx - 50;
direction = (int)(Math.random()*4);
}
if (sheepx <= 5){
direction = directionNumbersLeft[x];
}
if (xposR > (sheepx - 20)&& xposR < (sheepx - 20)+(sheepBoundsx - 20) && yposR > (sheepy - 20)
&& yposR < (sheepy - 20)+(sheepBoundsy - 20) && direction == 3){
sheepy = sheepy - 50;
direction = (int)(Math.random()*4);
}
if (sheepy <=5){
direction = directionNumbersUp[x];
}
xposR = e.getX();
yposR = e.getY();
repaint();
}
}
class Dog
{
int xpos;
int ypos;
int circleWidth = 30;
int circleHeight = 30;
public Dog(int x, int y)
{
xpos = x;
ypos = y;
}
public void setLocation(int lx, int ly)
{
xpos = lx;
ypos = ly;
}
public void display(Graphics g)
{
g.setColor(Color.blue);
g.fillOval(xpos, ypos, circleWidth, circleHeight);
}
}
class Sheep
{
int xpos;
int ypos;
int circleWidth = 10;
int circleHeight = 10;
public Sheep(int x, int y)
{
xpos = x;
ypos = y;
}
public void setLocation(int lx, int ly)
{
xpos = lx;
ypos = ly;
}
public void display(Graphics g)
{
g.setColor(Color.green);
g.fillOval(xpos , ypos, circleWidth, circleHeight);
g.drawOval(xpos - 20, ypos - 20, 50, 50);
}
}
First of all, I dont exactly understand why you have a display method inside your Sheep and Dog class. Instead of doing that, I suggest you display the sheep and dog inside your SheepDog class.
Also instead of using Graphics, you should use Graphics2D. In order to use this simply do
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
}
This is possible because Graphics2D is a subclass of Graphics. Once you do that, what I would do is override the update() method and do this
public void update(Graphics g) {
if (image == null) {
image = createImage(this.getWidth(), this.getHeight());
graphics = image.getGraphics();
}
graphics.setColor(getBackground());
graphics.fillRect(0, 0, this.getWidth(), this.getHeight());
graphics.setColor(getForeground());
paint(graphics);
g.drawImage(image, 0, 0, this);
}
When you call repaint(), it actually first calls the update() method, which in turn calls the paint() method. Towards the top of the class, you should declare
Image image;
Graphics graphics;