I am very new to developing with java but I have some general coding experience. I know wanted to draw a "picture/fractal" with a function I created. I got all the code done and I wanted to automatically move the "fractal" by just adding to the function XOFF, (I have a timer) now I wanted the variable to automatically increase so that it scrolls through the picture. I tried using repaint and revalidate but it doesnt work :(
and i know that i wrote MandelBrotSet even though it doesn't have anything to do with it ^^
package Pack1;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.Timer;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class Main extends JComponent implements ActionListener {
public static void main(String[] args) {
new Main();
}
public static final int WIDTH = 1000;
public static final int HEIGHT = 800;
public int XOFF = 0;
public int YOFF = 0;
private BufferedImage buffer;
private Timer timer;
public Main(){
buffer = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
timer = new Timer(10, this);
renderMandelBrotSet();
JFrame frame = new JFrame("Mandelbrot Set");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(true);
frame.getContentPane().add(this);
frame.pack();
frame.setVisible(true);
}
#Override
public void addNotify() {
setPreferredSize(new Dimension(WIDTH, HEIGHT));
timer.start();
}
public void renderMandelBrotSet() {
System.out.println(XOFF);
int vx = 0;
int vy = 0;
int zoom = 1;
for(int x = 0; x < WIDTH; x++)
for(int y = 0; y < HEIGHT; y++) {
vx = ((x - WIDTH/2));
vy = ((y - HEIGHT/2));
vx = vx + XOFF;
vy = vy + 0;
int color = (int) (Math.abs(vx)/Math.sqrt(Math.abs(vy))*(vx/zoom)); //calculatePoint((x - WIDTH/2), (y - HEIGHT/2) );
buffer.setRGB(x, y, color);
}
}
#Override
public void paint(Graphics g) {
g.drawImage(buffer, 0, 0, null);
}
#Override
public void actionPerformed(ActionEvent e) {
XOFF++;
renderMandelBrotSet();
revalidate();
repaint();
}
}
I hope the code makes sense..., I am sorry if I forgot to mention anything. Feel free to ask me if you need something.
I think addNotify is your problem. That method already does something, and the way you overrode it you don't seem to perform any of the actions that its documentation says it should. Just get rid of it, and move its code elsewhere.
This seems to work for me. I also slowed your timer down to 100 ms since I know from experience that Java Swing isn't really capable of updating as quickly as that. 100 ms to 250 ms is a good range for updating Swing.
I also got rid of revalidate because that's only for when a component is added or removed, or changes size. You only need to repaint since your image doesn't change size.
(Hovercraft pointed out that the code really should override paintComponent, not paint. He is quite correct; this is explained in the tutorial: https://docs.oracle.com/javase/tutorial/uiswing/painting/closer.html )
(And while I'm fixing stuff up I might as well point out that Swing is not thread safe, and the GUI creation (including the image and the timer) really needs to be done on the GUI thread.)
package quicktest;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.Timer;
/**
*
* #author Brenden
*/
public class MandelbrotSet {
}
class Main extends JComponent implements ActionListener {
public static void main(String[] args) {
new Main();
}
public static final int WIDTH = 800;
public static final int HEIGHT = 600;
public int XOFF = 0;
public int YOFF = 0;
private BufferedImage buffer;
private Timer timer;
public Main(){
SwingUtilities.invokeLater( this::createGui );
}
private void createGui() {
buffer = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
timer = new Timer(100, this);
setPreferredSize( new Dimension( WIDTH, HEIGHT ) );
renderMandelBrotSet();
JFrame frame = new JFrame("Mandelbrot Set");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(true);
frame.getContentPane().add(this);
frame.pack();
frame.setVisible(true);
timer.start();
}
// #Override
// public void addNotify() {
// setPreferredSize(new Dimension(WIDTH, HEIGHT));
// timer.start();
// }
public void renderMandelBrotSet() {
System.out.println(XOFF);
int vx = 0;
int vy = 0;
int zoom = 1;
for(int x = 0; x < WIDTH; x++)
for(int y = 0; y < HEIGHT; y++) {
vx = ((x - WIDTH/2));
vy = ((y - HEIGHT/2));
vx = vx + XOFF;
vy = vy + 0;
int color = (int) (Math.abs(vx)/Math.sqrt(Math.abs(vy))*(vx/zoom)); //calculatePoint((x - WIDTH/2), (y - HEIGHT/2) );
buffer.setRGB(x, y, color);
}
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent( g );
System.err.println( "Repainting..." );
g.drawImage(buffer, 0, 0, null);
}
#Override
public void actionPerformed(ActionEvent e) {
System.err.println( "Timer: XOFF=" + XOFF );
XOFF++;
renderMandelBrotSet();
// revalidate();
repaint();
}
}
Related
I am painting vehicle objects that I defined using the paintComponent().
Because the vehicles can move, I implement ActionListener and set a Timer() to trigger.
As a result, my vehicles can move. But it is kind of "shaking". When I keep resizing the window to call the paintComponent(), the movement becomes smooth. When I do not resize the window (not calling paintComponent), it gets skaking again. Why? How to fix it?
public class VehiclesComponent extends JComponent implements ActionListener{
private Vehicle[] vehicles;
private Timer timer;
public VehiclesComponent(int n){
vehicles = Vehicle.generateVehicle(n);
timer = new Timer(5,this);
}
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
for (int i=0; i<vehicles.length; i++) {
vehicles[i].draw(g2);
}
// may change later
timer.start();
}
#Override
public void actionPerformed(ActionEvent e){
//check collision in here
for (Vehicle v : vehicles) {
if (Vehicle.intersectsOther(v, vehicles)) {
v.collisionSideEffect();
}
}
//move all in here
for (Vehicle v : vehicles ) {
v.move();
}
repaint();
//?? repaint slower than paintComponent
}
}
Start by taking a look at Painting in AWT and Swing. Remember, repaint is only a suggest made to the RepaintManager, the RepaintManager may choose to consolidate multiple repaint calls into a smaller number of actual paint events.
Make sure you are calling super.paintComponent, otherwise you will end up with no end of strange paint artifacts.
Don't, directly or indirectly, modify the state of the component or ant other components from within any paint method, this will result in a new repaint request been made, which could lead to a cycle of paint events which could consume your CPU cycles. This means, don't call timer.start()!
Without a runable example to go by, I hobbled this together. Now this is animating 10, 000 individual Vehicles (rectangles), so it's massively over kill, but it should provide the point...
(the gif is only running at 7fps, not your 200fps)
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.Timer;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new VehiclesComponent(10000));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class VehiclesComponent extends JComponent implements ActionListener {
private Vehicle[] vehicles;
private Timer timer;
public VehiclesComponent(int n) {
vehicles = Vehicle.generateVehicle(n, getPreferredSize());
timer = new Timer(5, this);
timer.start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(400, 400);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
for (int i = 0; i < vehicles.length; i++) {
vehicles[i].draw(g2);
}
}
#Override
public void actionPerformed(ActionEvent e) {
//check collision in here
// for (Vehicle v : vehicles) {
// if (Vehicle.intersectsOther(v, vehicles)) {
// v.collisionSideEffect();
// }
// }
//move all in here
for (Vehicle v : vehicles) {
v.move(this.getSize());
}
repaint();
//?? repaint slower than paintComponent
}
}
public static class Vehicle {
protected static final int SIZE = 5;
protected static final Color[] COLORS = new Color[]{
Color.BLACK,
Color.BLUE,
Color.CYAN,
Color.DARK_GRAY,
Color.GREEN,
Color.MAGENTA,
Color.ORANGE,
Color.PINK,
Color.RED,
Color.WHITE,
Color.YELLOW
};
private int x = 0;
private int y = 0;
private int xDelta;
private int yDelta;
private Shape car;
private Color color;
public static Vehicle[] generateVehicle(int count, Dimension bounds) {
Vehicle[] vehicles = new Vehicle[count];
for (int index = 0; index < vehicles.length; index++) {
vehicles[index] = new Vehicle(bounds);
}
return vehicles;
}
public Vehicle(Dimension size) {
x = (int)(Math.random() * (size.width - SIZE));
y = (int)(Math.random() * (size.height - SIZE));
xDelta = (int)(Math.random() * 3) + 1;
yDelta = (int)(Math.random() * 3) + 1;
car = new Rectangle(SIZE, SIZE);
color = COLORS[(int)(Math.random() * COLORS.length)];
}
public void move(Dimension size) {
x += xDelta;
y += yDelta;
if (x < 0) {
x = 0;
xDelta *= -1;
} else if (x + SIZE > size.width) {
x = size.width - SIZE;
xDelta *= -1;
}
if (y < 0) {
y = 0;
yDelta *= -1;
} else if (y + SIZE > size.height) {
y = size.height - SIZE;
yDelta *= -1;
}
}
public void draw(Graphics2D g2) {
g2.translate(x, y);
g2.setColor(color);
g2.fill(car);
g2.translate(-x, -y);
}
}
}
You could also take a look at this example which renders upwards of 4500 images in random directions and demonstrates some optimisation techniques.
You can also take a look at this example which is capable of animating both in direction and rotation, upwards of 10, 000 images
I made a simple program in Java which draws a rectangle on a canvas. And then the rectangle starts moving along X-axis, from left to right.
But the timer.schedule() function is not working. Following is the code:-
package firstanimation;
import java.awt.*;
import java.util.Timer;
public class FirstAnimation {
public static void main(String[] args) {
Frame frame = new Frame("SomeRandomName");
frame.setBounds(50, 50, 700, 500);
frame.setBackground(Color.red);
MyCanvas canvas = new MyCanvas();
frame.add(canvas);
frame.setVisible(true);
Graphics graph = frame.getGraphics();
Timer timer = new Timer();
Task task = new Task(canvas, graph);
timer.schedule(task, 1000,1000);
}
}
package firstanimation;
import java.awt.*;
public class MyCanvas extends Canvas{
public int x,y,width,height;
public MyCanvas()
{
x = 0;
y = 0;
width = 50;
height = 50;
}
#Override
public void paint(Graphics g) {
g.setColor(Color.LIGHT_GRAY);
g.fillRect(x, y, width, height);
}
#Override
public void update(Graphics g) {
x+=10;
g.fillRect(x, y, width, height);
}
}
package firstanimation;
import java.util.TimerTask;
import java.awt.Graphics;
public class Task extends TimerTask{
private MyCanvas canvas;
private Graphics graphics;
public Task(MyCanvas can, Graphics g)
{
super();
canvas = can;
graphics = g;
canvas.paint(g);
}
#Override
public void run() {
canvas.update(graphics);
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
But the strange thing is... Every time i'm maximizing and restoring the frame, the box is moving.
Why is this happening?
"But the strange thing is... Every time i'm maximizing and restoring the frame, the box is moving. Why is this happening?"
Because repaint() is called when you resize which update the graphics, which you should be doing, instead of trying to call paint.
But...
Still many things wrong.
Seeing as this is your first animation (package firstanimation;), let me get you started in the right direction.
Don't use Canvas. Use JPanel or JComponent instead. When you do, don't override paint but paintComponent instead. Also make sure you call super.paintComponent so you aren't let with any paint artifact during the animation.
public class MyCanvas extends JPanel {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
//painting code
}
}
Never use getGraphics on a component to do any painting.
You shouldn't ever have to explicitly call paint. The paint[Component] method will be implicitly called for you. A simple call to repaint() will repaint the component.
I just realized you're using all AWT components. Don't use them, they're out-dated. Instead use Swing component. The majority of them are just prefixed with a J, like Frame -> JFrame. They are in the javax.swing.* package.
For animation use a javax.swing.Timer. You can see more at How to Use Timers. The basic construct is
Timer ( int delayInMillis, ActionListener listener )
where delayInMillis is the time to delay between ticks(in this case animations) and the ActionListener listens for "ticks". Each tick, the actionPerformed of the ActionListener is called. There, you can put the code to update any variables you use for animation.
I suggest you read the tutorials Performing Custom Painting to see the proper way to paint.
Here's a simple example with all the points above mentioned
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class AnimateBall extends JPanel {
private static final int D_W = 500;
private static final int D_H = 300;
private Ball ball;
public AnimateBall() {
Random rand = new Random();
int randX = rand.nextInt(D_W);
int randY = rand.nextInt(D_H);
ball = new Ball(randX, randY);
Timer timer = new Timer(15, new ActionListener() {
public void actionPerformed(ActionEvent e) {
ball.animate();
repaint();
}
});
timer.start();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
ball.drawBall(g);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(D_W, D_H);
}
public class Ball {
int x = 0;
int y = 0; // Current ball position
int dx = 4; // Increment on ball's x-coordinate
int dy = 4; // Increment on ball's y-coordinate
int radius = 15; // Ball radius
public Ball(int x, int y) {
this.x = x;
this.y = y;
}
Color color = new Color((int) (Math.random() * 256),
(int) (Math.random() * 256), (int) (Math.random() * 256));
public void drawBall(Graphics g) {
g.setColor(color);
g.fillOval(x - radius, y - radius, radius * 2, radius * 2);
}
public void animate() {
if (x < 0 || x > getWidth()) {
dx = -dx;
}
if (y < 0 || y > getHeight()) {
dy = -dy;
}
// Adjust ball position
x += dx;
y += dy;
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
frame.add(new AnimateBall());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
I have created a graph in a Java applet and I'm trying to get the g.fillRect to auto adjust with the screen. I want the first bar to be a third of the screen and then to halve in size for each other bar.
g.fillRect(xpos, 550, width, hight);
I seem to have a problem with getting a gap in between each bar. Could you give me a hand with this problem? Thanks in advance.
You have to compute the width of each individual bar, which is
barWidth = availableWidth / numberOfBars - 1
The "-1" will be the space that will be left between the bars, and thus, has to be added again when computing the actual coordinates. You could spend some time with the details there: When the numbers are not "nicely divisble", then the bars either have to have different widths, or you have to add a small margin at the left and right side to compensate for the odd size.
However, here is a quick sketch of one possible solution:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
public class BarChart
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
createAndShowGUI();
}
});
}
private static void createAndShowGUI()
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().setLayout(new BorderLayout());
final JSlider slider = new JSlider(1, 50, 3);
final BarChartPanel barChartPanel = new BarChartPanel();
slider.addChangeListener(new ChangeListener()
{
#Override
public void stateChanged(ChangeEvent e)
{
barChartPanel.setNumberOfBars(slider.getValue());
}
});
f.getContentPane().add(slider, BorderLayout.NORTH);
f.getContentPane().add(barChartPanel, BorderLayout.CENTER);
f.pack();
f.setSize(600,600);
f.setVisible(true);
}
}
class BarChartPanel extends JPanel
{
private int numberOfBars = 3;
void setNumberOfBars(int n)
{
this.numberOfBars = n;
repaint();
}
#Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.BLUE);
Random random = new Random(0);
int barWidth = getWidth() / numberOfBars - 1;
int barsWidth = numberOfBars * (barWidth+1);
int offsetX = (getWidth() - barsWidth) / 2;
for (int b=0; b<numberOfBars; b++)
{
int x = offsetX + b * (barWidth + 1);
int barHeight = random.nextInt(500);
int y = getHeight() - barHeight;
g.fillRect(x, y, barWidth, barHeight);
}
}
}
I was wondering if anybody here knows how to make a seamlessly endless loop with shapes using a timer. Basically I'm trying to make a new set of moving shapes while the current set of shapes is moving so that it looks like it's just infinitely moving along the top of the screen. I have tried the if statements alongside the public int getX(){return x;)}, but I have not succeeded in doing so. Maybe it's possible to have a second timer linked with a second set of shapes and set a delay time? (However, I do not know how to go about writing a second timer and I do not know how to set a delay, help me??)
Any solutions or suggestions?
Here is an example, notice how the set of shapes is redrawn after all of the shapes pass the screen. This is not what I want. I want it to appear as if it were infinitely running along the top of the screen in smooth succession.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ExampleLoop extends JPanel implements ActionListener {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new ExampleLoop());
frame.setVisible(true);
}
Timer timer = new Timer(50, this);
int x = 0, velX = 7;
// CHRISTMAS THEME :D
public void paintComponent(Graphics g) {
g.setColor(Color.RED);
g.fillRect(0, 0, 500, 500);
g.setColor(Color.GREEN);
for (int z = 0; z <= 500; z += 100)
g.fillRect(x + z, 0, 20, 20);
timer.start();
}
public void actionPerformed(ActionEvent e) {
if (x < 500) {
velX = velX;
x = x + velX;
}
else {
x = 0;
}
repaint();
}
}
I can't really figure out what going on in your code, but I reproduce the effect you're looking for. You can examine it. It runs.
What i did was make 5 different xPoints. You could have done this by using an array of int but I thouhgt it would be easier to read this way.
For each xPoint, I incremented each timer iteration. If the xPoint reached the screen width, I made it equal 0. Then repaint. I did that for all the points.
Code Edited: to use arrays and loops
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class GreenRects extends JPanel {
private static final int SCREEN_WIDTH = 500;
private static final int SCREEN_HEIGHT = 500;
private static final int OFFSET = 100;
private static final int SIZE = 20;
private static final int INC = 5;
int[] xPoints = new int[5];
public GreenRects() {
int x = 0;
for (int i = 0; i < xPoints.length; i++) {
xPoints[i] = x;
x += OFFSET;
}
Timer timer = new Timer(50, new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int i = 0; i < xPoints.length; i++) {
if (xPoints[i] + INC < SCREEN_WIDTH) {
xPoints[i] += INC;
} else {
xPoints[i] = 0;
}
}
repaint();
}
});
timer.start();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
g.fillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
g.setColor(Color.green);
for (int i = 0; i < xPoints.length; i++) {
g.fillRect(xPoints[i], 0, SIZE, SIZE);
}
}
public Dimension getPreferredSize() {
return new Dimension(SCREEN_WIDTH, SCREEN_HEIGHT);
}
public static void createAndShowGui() {
JFrame frame = new JFrame();
frame.add(new GreenRects());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
You can try this code in if clause
if (x < 80)
{
velX = velX;
x = x + velX;
}
I have a thread which drops a circle in the y direction. I want to now create several circles on screen dropping at the same time with random x positions.
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Goo
{
protected GooPanel gooPanel;
private boolean loop = true;
protected int width , height;
private int frameTimeInMillis = 50;
private RenderingHints renderingHints = new RenderingHints(
RenderingHints.KEY_ANTIALIASING , RenderingHints.
VALUE_ANTIALIAS_ON);
#SuppressWarnings("serial")
class GooPanel extends JPanel
{
public void paintComponent(Graphics g)
{
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHints(renderingHints);
draw(g2d);
}
}
public Goo()
{
this (800, 500);
}
public Goo(int w, int h)
{
width = w;
height = h;
JFrame frame = new JFrame ();
frame.setSize(width , height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gooPanel = new GooPanel ();
gooPanel.setPreferredSize(new Dimension(w, h));
frame.getContentPane ().add(gooPanel);
frame.pack();
frame.setVisible(true);
}
public void go()
{
while (loop)
{
gooPanel.repaint();
try
{
Thread.sleep(frameTimeInMillis);
} catch (InterruptedException e) {}
}
}
public void draw(Graphics2D g) {}
public void setFrameTime(int millis)
{
frameTimeInMillis = millis;
}
public Component getGooPanel ()
{
return gooPanel;
}
}
My FallingDrop class:
import java.awt.*;
public class FallingDrops extends Goo
{
double x, y, r;
int red, green, blue = 0;
Color a;
FallingDrops()
{
x = width / 2;
r = 10;
y = -r;
}
FallingDrops(double x)
{
this.x = x;
r = 10;
y = -r;
}
public void draw(Graphics2D g)
{
g.setColor(Color.GRAY);
g.fillRect(0, 0, width , height);
g.setColor(Color.WHITE);
g.fillOval ((int) (x - r), (int) (y - r), (int) (2 * r),
(int) (2 * r));
y++;
if (y - r > height)
y = -r;
}
public static void main(String [] args)
{
int num = 10;
Goo gooDrop [] = new FallingDrops[num];
for(int i = 0; i < gooDrop.length; i++)
{
double x = Math.random()*800;
gooDrop[i] = new FallingDrops(x);
System.out.println(x);
gooDrop[i].go();
}
}
}
At current, the loop fails to complete when the go() method is executed; thus only painting ONE object on screen, and not several as indicated in my loop. This is a simple fix I am sure. Any ideas what I am doing wrong?
The method go() never returns. when it is called on the first object in the array, it continues working infinitely. you should either make the repainting in a separate thread that is constantly repainting. or if you want repainting only when drops are added, then remove the while in your go method
public void go()
{
gooPanel.repaint();
try
{
Thread.sleep(frameTimeInMillis);
} catch (InterruptedException e) {}
}
this way it will returns after it had made a repaining and a pause.
while (loop) .. gooPanel.repaint();
Not the way to do custom painting. Establish a Swing Timer and call repaint() in the actionPerformed() method of the listener.
See the Custom Painting lesson in the tutorial for details and working examples.