我目前正在使用swingbot进行作业。我使用用户命令移动了我的矩形,我创建了2个新形状,但它们不会移动。我不确定我是否没有正确宣布它们或者发生了什么。任何帮助表示赞赏。
import javax.swing.JFrame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.Line2D;
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_CLOSE);
Robot r = new Robot();
frame.add(r);
// voila!
frame.setVisible(true);
// your Scanner-based command loop goes here
Scanner input = new Scanner(System.in);
int noend = 0;
System.out.println("Do you want to move this square up, down, left or right?:");
while(noend == 0)
{
String command = input.next();
if(command.equals("left"))
r.moveBot(-10,0);
if(command.equals("right"))
r.moveBot(10,0);
if(command.equals("down"))
r.moveBot(0,10);
if(command.equals("up"))
r.moveBot(0,-10);
}
// call methods on the Robot instance like w.moveBot(10,10) in response to
// user input
}
public static class Robot extends JComponent
{
private Rectangle rect = new Rectangle(10,10);
private Ellipse2D elps = new Ellipse2D.Double(10,10,10,10);
private Polygon poly = new Polygon();
public void paintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
// set the color
g2.setColor(Color.RED);
// draw the shape`
g2.fill(rect);
g2.setColor(Color.BLUE);
g2.fill(poly);
g2.setColor(Color.YELLOW);
g2.fill(elps);
int xPoly[] = {75,125,170,170,200,105,60};
int yPoly[] = {75,50,88,111,125,180,150};
poly = new Polygon(xPoly,yPoly,xPoly.length);
}
public void moveBot(int x, int y)
{
// move the rectangle
rect.translate(x,y);
poly.translate(WIDTH, HEIGHT);
elps.
// redraw the window
repaint();
}
}
}