I want to move the shapes at the same time. How can i do that? Any ideas or suggestions? Thanks.
__________________________________________________ __
import javax.swing.JFrame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import javax.swing.JComponent;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.Color;
import java.awt.Polygon;
import java.util.Scanner;
public class swingBot
{
public static void main(String[] args) {
// contruction of new JFrame object
JFrame frame = new JFrame();
// mutators
frame.setSize(400,400);
frame.setTitle("SwingBot");
// program ends when window closes
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOS E);
Robot r = new Robot();
frame.add(r);
// voila!
frame.setVisible(true);
// your Scanner-based command loop goes here
Scanner in = new Scanner(System.in);
System.out.println(" Enter up, down, left or right to move the rectangle: ");
String w = in.nextLine();
// your Scanner-based command loop goes here
while (true){
if ("down".equalsIgnoreCase(w)){
r.moveBot(0,10);
}
else if ("up".equalsIgnoreCase(w)){
r.moveBot(0,-10);
}
else if ("left".equalsIgnoreCase(w)){
r.moveBot(-10,0);
}
else if ("right".equalsIgnoreCase(w)){
r.moveBot(10,0);
}
// call methods on the Robot instance like w.moveBot(10,10) in response to
// user input
System.out.println(" Enter up, down, left or right to move the rectangle: ");
w = in.nextLine();
}
}
public static class Robot extends JComponent
{
private Rectangle rect = new Rectangle(20,20);
private Ellipse2D.Double oval = new Ellipse2D.Double(40,40,100,150);
private Line2D.Double line = new Line2D.Double(30,120,150,120);
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
// set the color
g2.setColor(Color.RED);
// draw the shape`
g2.fill(rect);
g2.draw(oval);
g2.fill(oval);
g2.draw(line);
g2.setColor(Color.GREEN);
int[] x = new int[]{10,50,130,170};
int[] y = new int[]{200,30,30,200};
g.drawPolygon (x, y, x.length);
}
public void moveBot(int x, int y)
{
// move the rectangle
rect.translate(x,y);
// redraw the window
repaint();
}
}
}