所以我的AP Comp。科学课我必须制作一个applet,我们必须使用单独的类文件来制作建筑物的天际线。目前我有一个窗口类,它有一个draw方法和一个打开窗口对象的方法。我想用keyListener打开窗口,但我不熟悉那些。
这是我有的Window类
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JComponent;
public class windows {
private int x,y,height,width;
public windows(){
x=0;
y=0;
height = 0;
width = 0;
}//default constructor
public windows(int x, int y, int height, int width){
this.x = x;
this.y = y;
this.height = height;
this.width = width;
}//windows constructor
public void windowDraw(Graphics g){
Color window = new Color(0x05030D);
g.setColor(window);
g.fillRect(x, y, width, height);
}//windowDraw
public void windowOn(Graphics g){
Color on = new Color(0xFFD200);
g.setColor(on);
g.fillRect(x, y, width, height);
}//window on
}//class
这是客户。我在里面有一些测试版画,我曾经玩过。
import java.applet.Applet;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;
//Matteo Sabato
public class TeenTitans_Client extends Applet implements KeyListener {
private final int APPLET_WIDTH = 1000;
private final int APPLET_HEIGHT = 700;
private final int HEIGHT_MIN = 400;
private final int VARIANCE = 40;
Tower main,top;//(x, y, height, width)
backGround ground;//x,y,height,width
windows Right, middleTop, Left, Bottom, Middle, Tip;
boolean power = false;
Listener on;
int key;
public void init(){
addKeyListener(this);
Random gen = new Random();
Color back = new Color(0x37E2EA);
setBackground(back);
setSize(APPLET_WIDTH,APPLET_HEIGHT);
main = new Tower(550,180,460,150);
top = new Tower(370,40,150,505);
ground = new backGround(-200,500,400,1800);
Right = new windows(380,50,130,130);
Left = new windows(735,50,130,130);
middleTop = new windows(520,50,130,205);
Bottom = new windows(560,490,140,130);
Middle = new windows(560,340,140,130);
Tip = new windows(560,190,140,130);
}
public void paint(Graphics g){
ground.circleDraw(g);
main.towerDraw(g);
top.towerDraw(g);
Left.windowDraw(g);
Right.windowDraw(g);
Bottom.windowDraw(g);
middleTop.windowDraw(g);
Middle.windowDraw(g);
Tip.windowDraw(g);
if (power == true)
On(g);
}//paint
@Override
public void keyPressed(KeyEvent e) {
// TODO Auto-generated method stub.
System.out.println(e.getKeyCode());
this.key = e.getKeyCode();
if (key==10){
power = true;
}
}//keyPressed
public void On(Graphics g){
Tip.windowOn(g);
}//On
@Override
public void keyReleased(KeyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void keyTyped(KeyEvent e) {
// TODO Auto-generated method stub
}
}//class
我遇到的问题是我不知道如何在客户端调用我的On方法因为我需要将Graphics g作为参数,哪些关键事件方法不能采取。如果我在其他地方制作一个循环,我就无法检查按键。我尝试了一些不同的方式,但我无法弄明白。