I'm trying to make a simle java program that draws a circle at the mouse localization, it gets the mouse X and Y coordinates but it doesn't draw anything, i tried to draw a String, a circle and a line but nothing worked, i changed the code a bit but it still doesn't works
class Test4 {
public static String a;
public static JFrame frame = new JFrame();
public static Point Gett(){
PointerInfo h = MouseInfo.getPointerInfo();
Point b = h.getLocation();
return b;
}
public void paintComponent(int x, int y, Graphics g) {
g.drawOval(x, y, 10, 10);
}
public static void main(String[] args) throws InterruptedException {
int h = 250;
int f = 200;
frame.setVisible(true);
frame.setSize(h, f);
frame.setLocationRelativeTo(null);
while(true){
Point b = Gett();
int x = (int) b.getX();
int y = (int) b.getY();
System.out.println(x);
System.out.println(y);
frame.repaint();}}}
Don't perform custom painting directly on a JFrame. Always do it on a JComponent overriding the paintComponent method if you can.
Don't use an infinite loop for this purpose. There is the MouseMotionListener for Mouse Motion listening
public class Test4 {
public static String a;
public static CustomDrawingPanel content;
public static JFrame frame = new JFrame();
final static int OVAL_WIDTH = 10;
final static int OVAL_HEIGHT = 10;
static int x = -20, y = -20;
public static MouseMotionListener listener = new ContentListener();
public static void main(String[] args) throws InterruptedException {
int h = 250;
int f = 200;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
content = new CustomDrawingPanel();
content.addMouseMotionListener(listener);
frame.add(content);
frame.getContentPane().setPreferredSize(new Dimension(h, f));
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
//class that performs custom drawing
static class CustomDrawingPanel extends JPanel {
public void paintComponent(Graphics g) {
super.paintComponent(g); //Always call this
g.drawOval(x, y, 10, 10);
}
}
//listener to the mouse motion
static class ContentListener implements MouseMotionListener {
#Override
public void mouseDragged(MouseEvent e) {
mouseMoved(e); //if you delete this line, when you drag your circle will hang
}
#Override
public void mouseMoved(MouseEvent e) {
x = e.getX() - OVAL_WIDTH / 2;
y = e.getY() - OVAL_HEIGHT / 2;
content.repaint();
}
}
}
Related
I am trying to move a train across my java window and am having serious problems. I have a Train class in which I made the train, and a Driver class which is supposed to move the train. I need to make the whole train move from right to left until it 'passes' the left edge of the screen. Then add an if statement to change the dx so the train restarts on the right side . The below is what I have tried but it is not working. Can anyone help me please??
public class Driver extends GraphicsProgram
{
//~ Instance/static variables .............................................
private static final int N_STEPS = 1000;
private static final int PAUSE_TIME = 20;
private static final double TRAIN_LENGTH = 320;
//~ Constructor ...........................................................
// ----------------------------------------------------------
/**
* The run() method of the Driver Class.
* Creates an instance of the Train Class.
* Responsible for animating the train across the screen.
*/
public void run()
{
Train train = new Train(getGCanvas());
for (int i = 0; i < N_STEPS; i++) {
train.move(-100, 0);
pause(PAUSE_TIME);
}
Here is a little demo made with swing. Just replace the black rectangle with an image of your train and you're done.
The trick is to use a separate thread (or timer) to do the animation loop (often called game loop). The loop only tells your window to redraw itself, and on each redraw, you first compute the new positions of the animated objects, then you draw them.
import javax.swing.*;
import java.awt.*;
public class TrainDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("Train Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(800, 400);
frame.setLocationRelativeTo(null);
frame.add(new TrainCanvas());
frame.setVisible(true);
}
}
class TrainCanvas extends JComponent {
private int lastX = 0;
public TrainCanvas() {
Thread animationThread = new Thread(new Runnable() {
public void run() {
while (true) {
repaint();
try {Thread.sleep(10);} catch (Exception ex) {}
}
}
});
animationThread.start();
}
public void paintComponent(Graphics g) {
Graphics2D gg = (Graphics2D) g;
int w = getWidth();
int h = getHeight();
int trainW = 100;
int trainH = 10;
int trainSpeed = 3;
int x = lastX + trainSpeed;
if (x > w + trainW) {
x = -trainW;
}
gg.setColor(Color.BLACK);
gg.fillRect(x, h/2 + trainH, trainW, trainH);
lastX = x;
}
}
color c = color(0); float x = 0; float y = 100; float speed = 1;
void setup() { size(200,200); }
void draw() { background(255); move(); display(); }
void move() { x = x + speed; if (x > width) { x = 0; } }
void display() { fill(c); rect(x,y,30,10); }
I'm trying to create a program that runs an animation similar to the one on this video but I'm having trouble adding more squares. I tried to add all the squares to an array list but I couldn't figure out where it goes.
so far this is my code:
public class Animation extends JFrame{
CrazySquares square = new CrazySquares();
Animation(){
add(new CrazySquares());
}
public static void main (String[] args){
Animation frame = new Animation();
frame.setTitle("AnimationDemo");
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(250, 250);
frame.setVisible(true);
}
}
class CrazySquares extends JPanel{
private final int numberOfRectangles=100;
Color color=new Color((int)(Math.random()*256),(int)(Math.random()*256),(int)(Math.random()*256));
private int x=1;
private int y=1;
private Timer timer = new Timer(30, new TimerListener());
Random random= new Random();
int randomNumber=1+(random.nextInt(4)-2);
Random rand= new Random();
int rando=1+(rand.nextInt(4)-2);
CrazySquares(){
timer.start();
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int width=getWidth();
int height=getHeight();
g.setColor(color);
g.fillRect(x+width/2,y+(int)(height*.47), 20, 20);
}
class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
x += rando;
y+= randomNumber;
repaint();
}
}
}
You've got code to paint out one rectangle, here:
int width=getWidth();
int height=getHeight();
g.setColor(color);
g.fillRect(x+width/2,y+(int)(height*.47), 20, 20);
Now what I would recommend, would be that you port these values into a Square object. Or, better yet, use the Rectangle object. If you went with the custom approach:
public class Square
{
public Square(int x, int y, int height, int width)
{
// Store these values in some fields.
}
public void paintComponent(Graphics g)
{
g.fillRect() // Your code for painting out squares.
}
}
Then, all you need to do, is call each object's paintComponent method in some list. Let's assume you have some List:
List<Square> squares = new ArrayList<Square>();
for(Square sq : squares)
{
sq.paintComponent(g);
}
this is the code so far. I know its nasty but its because i've been trying different things a none of them work. i really appreciate your help. thanks. #ChrisCooney
public class SquaresAnimation extends JFrame{
SquaresAnimation(){
add(new CrazySquares());
}
public static void main (String[] args){
SquaresAnimation frame = new SquaresAnimation();
frame.setTitle("AnimationDemo");
frame.setLocationRelativeTo(null); // Center the frame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(250, 250);
frame.setVisible(true);
}
}
class Square{
private int x;
private int y;
public int height;
public int width;
Square(int x, int y, int height, int width)
{
// Store these values in some fields.
this.x=x;
this.y=y;
this.height=height;
this.width=width;
}
public void paintComponent(Graphics g)
{
g.setColor(Color.CYAN);
g.fillRect(x+width/2,y+(int)(height*.47), 20, 20);
}
}
class CrazySquares extends JPanel {
private final int numberOfRectangles=100;
Color color=new Color((int)(Math.random()*256),(int)(Math.random()*256),(int)(Math.random()*256));
private int x=1;
private int y=1;
Random random= new Random();
int randomNumber=1+(random.nextInt(4)-2);
Random rand= new Random();
int rando=1+(rand.nextInt(4)-2);
private Timer timer = new Timer(30, new TimerListener());
List<Square> squares = new ArrayList<Square>();
CrazySquares(Graphics g){
timer.start();
for(Square sq : squares){
sq.paintComponent(g);
}
}
}
//protected void paintComponent(Graphics g) {
//super.paintComponent(g);
// }
class TimerListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
repaint();
}
}
I've been trying to get this rectangle to move that I've created using a for loop. All that's happening with this code is that there is an original rectangle and then a new one next to that rectangle. No animation happens, only those two rectangles show on the window. What are some methods to get this rectangle to animate?
import java.awt.*;
import javax.swing.*;
public class Gunman extends JComponent {
/**
*
*/
private static final long serialVersionUID = 1L;
public int x = 10;
public int y = 10;
public int width = 8;
public int height = 10;
public void paint(Graphics g) {
g.setColor(Color.red);
g.drawRect (x, y, width, height);
g.fillRect (x, y, width, height);
for(int i = 0; i<=1024; i++){
g.setColor(Color.red);
g.drawRect(x++, y, width, height);
g.fillRect(x++, y, width, height);
}
}
}
Don't have program logic in a paint or paintComponent method, and by logic, I mean the for loop with "motion" as that just won't work. You want to
Almost never draw in a JComponent's paint method but rather in its paintComponent method.
Don't forget to call the super.paintComponent(g) method too, often as the first method call in the paintComponent(g) override.
Use a Swing Timer to step wise change the x and y values
call repaint() on the JComponent after the changes are made
For example
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Gunman extends JComponent {
private static final long serialVersionUID = 1L;
private static final int PREF_W = 900;
private static final int PREF_H = 700;
private static final int TIMER_DELAY = 30;
public int rectX = 10;
public int rectY = 10;
public int width = 8;
public int height = 10;
public Gunman() {
new Timer(TIMER_DELAY, new ActionListener() {
#Override
public void actionPerformed(ActionEvent actEvt) {
if (rectX < PREF_W && rectY < PREF_H) {
rectX++;
rectY++;
repaint();
} else {
((Timer)actEvt.getSource()).stop();
}
}
}).start();
}
#Override
public Dimension getPreferredSize() {
return new Dimension(PREF_W, PREF_H);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
g.drawRect(rectX, rectY, width, height);
g.fillRect(rectX, rectY, width, height);
}
public int getRectX() {
return rectX;
}
public void setRectX(int rectX) {
this.rectX = rectX;
}
public int getRectY() {
return rectY;
}
public void setRectY(int rectY) {
this.rectY = rectY;
}
private static void createAndShowGui() {
Gunman mainPanel = new Gunman();
JFrame frame = new JFrame("Gunman");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
There are numerous ways to animate. Here is another example. Notice the location of repaint() inside a background thread. This paints directly on a JFrame. Use paintComponent() when painting on JPanels.
public static void main(String args[]) throws Exception {
new JFrame("Draw a red box") {
Point pointStart = new Point(50,50);
Point pointEnd = new Point(200,200);
public void paint(Graphics g) {
super.paint(g);
if (pointStart != null) {
g.setColor(Color.RED);
g.drawRect(pointStart.x, pointStart.y, pointEnd.x, pointEnd.y);
}}{
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setSize(300, 300);
setLocation(300, 300);
setVisible(true);
Thread t = new Thread(new Runnable() {
public void run() {
while (pointEnd.x > 0 && pointEnd.y > 0) {
pointEnd = new Point(--pointEnd.x, --pointEnd.y);
repaint();
try {
Thread.sleep(22);
} catch (InterruptedException e) {
e.printStackTrace();
}}
pointStart = null;
pointEnd = null;
}});
t.setDaemon(true);
t.start();
}};}
UPDATE: Ok previous answer was not so good from the old memory, here is the quickest, cheapest, most dirty way to get some animation quicksmart, you can copy and compile the code as is:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class Test extends JFrame {
public Gunman g = new Gunman();
public static void main( String[] args ) {
Test t = new Test();
t.setSize( 800, 600 );
t.setVisible( true );
t.getContentPane().add( t.g );
while ( true ) {
t.g.x = t.g.x + 1;
t.g.y = t.g.y + 1;
t.repaint();
try {
Thread.sleep( 100 );
} catch ( InterruptedException e ) {
}
}
}
public void paintComponent( Graphics g ) {
g.clearRect( 0, 0, 800, 600 );
}
}
class Gunman extends JComponent {
private static final long serialVersionUID = 1L;
public int x = 10;
public int y = 10;
public int width = 8;
public int height = 10;
public void paintComponent( Graphics g ) {
g.setColor( Color.red );
g.fillRect( x, y, width, height );
}
}
There are ALOT of shortcuts in this, as Hovercraft of Eels has said, this is not an 'ideal' way to do it, but it has the basic structure. You have a canvas (I have used the JFrame, again not really recommended), and you add a component to it. You must override paintComponent (if you are using swing, which I do recommend you do), and this will draw your component.
You then need to alter your component's position in some way (recommend a proper method call on the object that does this), and ask the canvas to repaint itself.
I have included the wait so you can see what's happening, but if you are thinking of game programming, you should look into creating a game loop to manage this, I recommend Killer game programming in java, you can get a free ebook version with a quick google search.
I have a problem in my application using line primitives and JLables. I try to explain it:
I have to draw a vehicle route using lines to represent roads and JLabels to represent cities. I need the use of JLabels because each JLabel has a Listener that shows a dialog with information about the city.
I redefine paint() method of my main JPanel. In that method I first in invoke the super.paint(), then I draw the lines and finally I add the Labels to the JPanel.
The problem is that the lines overlap the labels regardless the matter the order of painting them. Is there any suggestion?
You can also override paintComponent() or paintChildren() methods of the JPanel.
In the paintChildren() call your lines drawing and then super to draw JLabels.
anothe way should be
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.Ellipse2D;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
public class AddVertexDemo {
public AddVertexDemo() {
}
private static void createAndShowUI() {
JFrame frame = new JFrame("AddVertexDemo");
frame.getContentPane().add(new Gui().getMainPanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
createAndShowUI();
}
});
}
}
class DrawingPanel extends JPanel {
private static final int RADIUS = 6;
private static final long serialVersionUID = 1L;
private List<Shape> vertexList = new ArrayList<Shape>();
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
if (vertexList.size() > 1) {
Shape s0 = vertexList.get(0);
Shape s1 = null;
for (int i = 0; i < vertexList.size(); i++) {
s1 = vertexList.get(i);
drawConnectingLine(g, s0, s1);
s0 = s1;
}
s1 = vertexList.get(0);
//drawConnectingLine(g2, s0, s1);
}
for (Shape shape : vertexList) {
g2.setColor(Color.blue);
g2.fill(shape);
g2.setColor(Color.blue.darker().darker());
g2.draw(shape);
}
}
private void drawConnectingLine(Graphics g, Shape s0, Shape s1) {
Rectangle r0 = s0.getBounds();
Rectangle r1 = s1.getBounds();
int x0 = r0.x + r0.width / 2;
int y0 = r0.y + r0.height / 2;
int x1 = r1.x + r1.width / 2;
int y1 = r1.y + r1.height / 2;
g.drawLine(x0, y0, x1, y1);
}
public void addVertex(Point p) {
int x = p.x - RADIUS;
int y = p.y - RADIUS;
int w = 2 * RADIUS;
int h = w;
vertexList.add(new Ellipse2D.Double(x, y, w, h));
repaint();
}
public void removeVertex(Point p) {
if (vertexList.size() > 0) {
for (int i = vertexList.size() - 1; i >= 0; i--) {
if (vertexList.get(i).contains(p)) {
vertexList.remove(i);
repaint();
return;
}
}
}
}
}
class Gui {
private static final Dimension DRAWING_PANEL_SIZE = new Dimension(600, 500);
private JPanel mainPanel = new JPanel(new BorderLayout());
private DrawingPanel drawingPanel = new DrawingPanel();
private JToggleButton addVertexBtn = new JToggleButton("Add Vertex");
private JToggleButton removeVertexBtn = new JToggleButton("Remove Vertex");
Gui() {
JPanel buttonPanel = new JPanel();
buttonPanel.add(addVertexBtn);
buttonPanel.add(removeVertexBtn);
DrawPanelMouseListener mouseListener = new DrawPanelMouseListener();
mouseListener.setDrawingPanel(drawingPanel);
mouseListener.setGui(this);
drawingPanel.addMouseListener(mouseListener);
drawingPanel.setPreferredSize(DRAWING_PANEL_SIZE);
drawingPanel.setBorder(BorderFactory.createLineBorder(Color.black));
mainPanel.add(drawingPanel, BorderLayout.CENTER);
mainPanel.add(buttonPanel, BorderLayout.SOUTH);
}
public JPanel getMainPanel() {
return mainPanel;
}
public boolean isAddingVertex() {
return addVertexBtn.isSelected();
}
public boolean isRemovingVertex() {
return removeVertexBtn.isSelected();
}
public void setAddingVertex(boolean addingVertex) {
addVertexBtn.setSelected(addingVertex);
}
public void setRemovingVertex(boolean removingVertex) {
removeVertexBtn.setSelected(removingVertex);
}
}
class DrawPanelMouseListener extends MouseAdapter {
private DrawingPanel drawingPanel;
private Gui gui;
public DrawPanelMouseListener() {
}
public void setGui(Gui gui) {
this.gui = gui;
}
public void setDrawingPanel(DrawingPanel drawingPanel) {
this.drawingPanel = drawingPanel;
}
#Override
public void mousePressed(MouseEvent me) {
if (gui.isAddingVertex() && gui.isRemovingVertex()) {
gui.setAddingVertex(false);
gui.setRemovingVertex(false);
return;
}
if (gui.isAddingVertex()) {
drawingPanel.addVertex(me.getPoint());
gui.setAddingVertex(false);
}
if (gui.isRemovingVertex()) {
drawingPanel.removeVertex(me.getPoint());
gui.setRemovingVertex(false);
}
}
}
I'm not sure that this is the right way to do this but you can try this:
Create 2 panels. One for drawing lines and another for drawing buildings(labels).
Add both panels in LayeredPane of JFrame. Add panel with line in lower layer then panel with labels.
You can use LayeredPanes in other ways also to solve your problem. Learn more here: How to use Layered Panes in java
UPDATE: semicomplex animation + swing timer = trainwreck. The ultimate source of the problems was the java timer, either the swing or utility version. They are unreliable, especially when performance is compared across operating systems. By implementing a run-of-the-mill thread, the program runs very smoothly on all systems. http://zetcode.com/tutorials/javagamestutorial/animation/. Also, adding Toolkit.getDefaultToolkit().sync() into the paintComponent() method noticeably helps.
I wrote some code that animated smoothly in an awt.Applet (but flickered), then I refactored it to java swing. Now it doesn't flicker but it looks choppy. I've messed with the timer but that doesn't work. Any tips or suggestions for smoothly animating swing components would be greatly appreciated.
import java.util.Random;
import java.util.ArrayList;
import java.awt.event.;
import java.awt.;
import javax.swing.*;
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
public class Ball extends JApplet{
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame frame = new JFrame();
frame.setTitle("And so the ball rolls");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initContainer(frame);
frame.pack();
frame.setVisible(true);
}
});
}
public static void initContainer(Container container){
GraphicsPanel graphicsPanel = new GraphicsPanel();
MainPanel mainPanel = new MainPanel(graphicsPanel);
container.add(mainPanel);
graphicsPanel.startTimer();
}
#Override
public void init(){
initContainer(this);
}
}
///////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
class MainPanel extends JPanel {
JLabel label = new JLabel("Particles");
GraphicsPanel gPanel;
public MainPanel(GraphicsPanel gPanel){
this.gPanel = gPanel;
add(gPanel);
add(label);
}
}
///////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
class GraphicsPanel extends JPanel implements MouseListener {
private ArrayList<Particle> ballArr = new ArrayList<Particle>();
private String state="s"; //"s"=spiral, "p"=particle
private int speed=10; //~20 Hz
private Timer timer;
public GraphicsPanel(){
System.out.println("echo from gpanel");
setPreferredSize(new Dimension(500,500));
timer = new Timer(speed, new TimerListener());
addMouseListener(this);
}
public void startTimer(){
timer.start();
}
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
for (Particle b: ballArr){
g.setColor(b.getColor());
g.fillOval(b.getXCoor(),b.getYCoor(),
b.getTheSize(),b.getTheSize());
}
}
public void mousePressed(MouseEvent e) {
ballArr.add(new Particle(e.getX(), e.getY(), state));
}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mouseClicked(MouseEvent e) {}
class TimerListener implements ActionListener {
public void actionPerformed(ActionEvent e){
for (Particle b: ballArr)
b.move();
setBackground(Color.WHITE);
repaint();
}
}
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
class Particle
{
private static int instanceCount; {{instanceCount++;}}
private int z = 11, t=1, u=1;
private int[] RGB = new int[3];
private int[] randomizeColor = new int[3];
private double radius, theta;
private int x, y, centerX, centerY, size, spiralDirection=1,
ballSizeLowerBound, ballSizeUpperBound,
radiusLowerBound, radiusUpperBound,
mouseInputX, mouseInputY,
radiusXMultiplier, radiusYMultiplier;
private Color color;
private String state;
private Random random = new Random();
///////////////////////////////////////////////////////////////////////////
public Particle(int x, int y, int centerX, int centerY, int radius,
int theta, int size, Color color){
this.x=x;this.y=y;this.centerX=centerX;this.centerY=centerY;
this.radius=radius;this.theta=theta;this.size=size;this.color=color;
}
public Particle(int mouseInputX, int mouseInputY, String state){
this.mouseInputX=mouseInputX;
this.mouseInputY=mouseInputY;
this.state=state;
//randomize color
RGB[0] = random.nextInt(252);
RGB[1] = random.nextInt(252);
RGB[2] = random.nextInt(252);
randomizeColor[0] = 1+random.nextInt(3);
randomizeColor[0] = 1+random.nextInt(3);
randomizeColor[0] = 1+random.nextInt(3);
centerX=mouseInputX;
centerY=mouseInputY;
if (state.equals("s")){ //setup spiral state
ballSizeLowerBound=5;
ballSizeUpperBound=18;
radiusLowerBound=0;
radiusUpperBound=50;
radiusXMultiplier=1;
radiusYMultiplier=1;
}
if (state.equals("p")){ //setup particle state
ballSizeLowerBound = 15;
ballSizeUpperBound =20 + random.nextInt(15);
radiusLowerBound = 5;
radiusUpperBound = 15+ random.nextInt(34);
radiusXMultiplier=1 + random.nextInt(3);
radiusYMultiplier=1 + random.nextInt(3);
}
size = ballSizeUpperBound-1; //ball size
radius = radiusUpperBound-1;
if (instanceCount %2 == 0) // alternate spiral direction
spiralDirection=-spiralDirection;
}
///////////////////////////////////////////////////////////////////////////
public int getXCoor(){return centerX+x*spiralDirection;}
public int getYCoor(){return centerY+y;}
public int getTheSize(){return size;}
public Color getColor(){return color;}
//////////////////////////////////////////////////////////////////////////
void move(){
//spiral: dr/dt changes at bounds
if (radius > radiusUpperBound || radius < radiusLowerBound)
u = -u;
//spiral shape formula: parametric equation for the
//polar equation radius = theta
x = (int) (radius * radiusXMultiplier * Math.cos(theta));
y = (int) (radius * radiusYMultiplier * Math.sin(theta));
radius += .1*u;
theta += .1;
//ball size formula
if (size == ballSizeUpperBound || size == ballSizeLowerBound)
t = -t;
size += t;
//ball colors change
for (int i = 0; i < RGB.length; i++)
if (RGB[i] >= 250 || RGB[i] <= 4)
randomizeColor[i] = -randomizeColor[i];
RGB[0]+= randomizeColor[0];
RGB[1]+= randomizeColor[1];
RGB[2]+= randomizeColor[2];
color = new Color(RGB[0],RGB[1],RGB[2]);
}
}
Don't set a constant interval timer. Set the timer to go off once -- in the handler
Get the current time (save in frameStartTime)
Do your frame
Set the timer to go off in: interval - (newCurrentTime - frameStartTime)
Should be smoother. If you want to go really pro (and stay in Java), I think you have to consider JavaFX.