【发布时间】:2020-11-21 21:26:27
【问题描述】:
我正在使用 Java 开发黄昏清洁器模拟器,在这种情况下清洁器的形状是一个圆形球。
程序很简单,用户输入“房间”的宽度和长度以及坐标x和y。
我想要做和不能的是创建一系列命令,每个命令都由一个字符表示。我想实现三个命令:
1. char 'A' = 向前移动 1 米
2。 char 'L' = 左转 90 度
3. R 右转 90 度
用户输入示例AALA,在这种情况下,预期的输出是机器移动 2 米,然后左转 90 度,然后再次移动 1 米。希望我清楚。
正如您在代码中看到的,我尝试创建一个字符数组,但我不知道下一步应该是什么......
代码:
public class Cleaner extends JPanel {
/* int lx = 1, ly = 1;
int x = 200, y = 250;
*/
int x, y;
int width = 52, height = 50; // width and height of the "dust sucker"
int lx , ly;
// an array of chars
char[] charArray ={ 'A', 'L', 'R'};
java.util.Timer move; // making the instance of Timer class from the util package
static JFrame frame;
Cleaner()
{
frame = new JFrame ("Cleaner started!"); // passing attributes to our fame
frame.setSize (400, 400); // setting size of the starting window
frame.setVisible (true);
setForeground(Color.black); // setting color
move = new java.util.Timer();
move.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
if(x<0)
lx = 1;
if(x>=getWidth()-45)
lx = -1; // -1 sets boundry for the dusk sucker
if(y<0)
ly = 1;
if(y>=getHeight()-45)
ly = -1; // -1 sets boundry for the dusk sucker
x+=lx; // to make the machine move
y+=ly;
repaint();
}
}, 0, 5// speed of the machine
);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void paint (Graphics g)
{
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.fillOval(x, y, width, height);
}
public static void main (String[] args)
{
// lx value
String lxValue =
JOptionPane.showInputDialog( "Enter lx" );
// ly value
String lyValue =
JOptionPane.showInputDialog( "Enter ly" );
String xValue =
JOptionPane.showInputDialog( "Enter x value" );
// ly value
String yValue =
JOptionPane.showInputDialog( "Enter y value" );
// convert String inputs to int values
int firstInput = Integer.parseInt( lxValue );
int secondInput = Integer.parseInt( lyValue );
int thirdInput = Integer.parseInt( xValue );
int forthInput = Integer.parseInt( yValue );
Cleaner cleaner = new Cleaner();
frame.add(cleaner);
cleaner.lx = firstInput;
cleaner.ly = secondInput;
cleaner.x = thirdInput;
cleaner.y = forthInput;
}
}
感谢所有帮助!
【问题讨论】:
标签: java swing graphics command