public class TestDrawFrame { public static void main(String[] args) {
new frame("test draw frame");
}}class frame extends Frame {
ArrayList<Point> al = null; frame(String s) {
super(s);
al = new ArrayList();
this.setLayout(null);
Button b = new Button("ok");
b.setBounds(50, 50, 200, 200);
this.setSize(500, 500);
this.setLocation(300, 300);
this.setBackground(Color.gray);
this.add(b);
this.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
int i = e.getKeyCode();
if (i == (KeyEvent.VK_UP)) {
System.out.println("dsfasfddsafsaf");
}
}});
this.addMouseListener(new mouseclick());
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
setVisible(false);
System.exit(0);
} });
this.setVisible(true);
}
public void addpoint(Point p) {
al.add(p);
} public void paint(Graphics g) {
Iterator i = al.iterator();
while (i.hasNext()) {
Point p = (Point) i.next();
g.setColor(Color.yellow);
g.fillOval(p.x, p.y, 20, 20);
}
} class mouseclick extends MouseAdapter {
public void mousePressed(MouseEvent e) {
frame t = (frame) e.getSource();
t.addpoint(new Point(e.getX(), e.getY()));
t.repaint();
}
}}
new frame("test draw frame");
}}class frame extends Frame {
ArrayList<Point> al = null; frame(String s) {
super(s);
al = new ArrayList();
this.setLayout(null);
Button b = new Button("ok");
b.setBounds(50, 50, 200, 200);
this.setSize(500, 500);
this.setLocation(300, 300);
this.setBackground(Color.gray);
this.add(b);
this.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
int i = e.getKeyCode();
if (i == (KeyEvent.VK_UP)) {
System.out.println("dsfasfddsafsaf");
}
}});
this.addMouseListener(new mouseclick());
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
setVisible(false);
System.exit(0);
} });
this.setVisible(true);
}
public void addpoint(Point p) {
al.add(p);
} public void paint(Graphics g) {
Iterator i = al.iterator();
while (i.hasNext()) {
Point p = (Point) i.next();
g.setColor(Color.yellow);
g.fillOval(p.x, p.y, 20, 20);
}
} class mouseclick extends MouseAdapter {
public void mousePressed(MouseEvent e) {
frame t = (frame) e.getSource();
t.addpoint(new Point(e.getX(), e.getY()));
t.repaint();
}
}}
@Override
public Component getDefaultComponent(Container container) {
return frame.this;
}
});设置Frame本身是默认焦点的持有者,那么你的键盘监听就生效了