我在小程序中使用draw方法制作了一个小型宇宙飞船。
我正在使用x和y在applet框周围移动船。
所以我想我会更好地自我并尝试添加textfield
以及一个动态更改x n y的按钮,但是当我单击按钮时
宇宙飞船保持不动。这是我的代码:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.applet.*;
public class SpaceshipInAJApplet extends Applet implements ActionListener {
int x = 65;
int y = 100;
TextField x1,y1;
Button enter;
public void init() {
setBackground(new Color(0xabcdef));
x1 = new TextField("X : " + x, 5);
y1 = new TextField("Y : " + y, 5);
add(x1);
add(y1);
setSize(500, 500);
enter = new Button("Enter");
add(enter);
enter.addActionListener(this);
}
// Creates Class Called paint to draw objects into the applet
public void paint(Graphics g) {
int []flameX = {x+65,x+75,x+55};
int []flameY = {y+185,y+161,y+161};
int []wingX = {x+65,x+120,x+15};
int []wingY = {y+50,y+150,y+150};
super.paint(g);
// Draw Wing
g.setColor(Color.LIGHT_GRAY);
g.fillPolygon(wingX, wingY, 3);
// Draw Wing Border
g.setColor(Color.BLACK);
g.drawPolygon(wingX, wingY, 3);
// Draw Body
g.setColor(Color.LIGHT_GRAY);
g.fillRect(x+50, y+85, 30, 65);
// Draw Border
g.setColor(Color.BLACK);
g.drawRect(x+50, y+85, 30, 65);
// Draw Rocket
g.setColor(Color.LIGHT_GRAY);
g.fillRect(x+55, y+150, 20, 10);
// Draw Border
g.setColor(Color.BLACK);
g.drawRect(x+55, y+150, 20, 10);
// Draw Rocket Flame
g.setColor(Color.ORANGE);
g.fillPolygon(flameX, flameY, 3);
}
public void actionPerformed(ActionEvent ae)
{
try {
int tempX = Integer.parseInt(x1.getText());
int tempY = Integer.parseInt(y1.getText());
}
catch(NumberFormatException ex)
{
System.out.println("Exception : "+ex);
}
}
}
答案 0 :(得分:2)
在 actionPerformed()方法中添加 This.repaint(),