问题 问答题

以下程序中,当用户单击“移动”按钮以后,就可以使用方向键控制屏幕上句子的移动,单击“停止”按钮,则句子不再随着方向键移动。运行结果如下图所示


注意:请勿改动其他已有语句内容,仅在横线处填入适当语句。
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Example2_8 extends Applet implements KeyListener

public void keyTyped(KeyEvent e)
public void keyReleased(KeyEvent e)
Button button;
Button stopButton;
Label out;
int x,y;
public void _______ ()

button = new Button("移动");
button.addActionListener(new AddMoveListener(this));
stopButton = new Button("停止移动");
stopButton.addActionListener(new RemoveListener(this));
stopButton.setEnabled(false);
out = new nabel("按下按钮以后我可以随方向键移动");
add(button);
add(stopButton);
add (out);

public void start()

super, start ();

public void keyPressed(KeyEvent e)

x=out.getBounds().x;
y=out.getBounds().y;
if(e.getKeyCode()==KeyEvent.VK_UP)

y=y-2;
if(y<=0) y=0;
out. setLocation (x, y);

else if(e.getKeyCode()==KeyEvent.VK_DOWN)

y=y+2;
if (y>=300) y=300;
out. setLocation (x, y);

else if(e.getKeyCode()==KeyEvent.VK_LEFT)

x=x-2;
if(x<=0) x=0;
out. setLocation (x, y);

else if(e.getKeyCode()==KeyEvent.VK_RiGHT)

x=x+2;
if(x>=300) x=300;
out. setLocation (x, y);


class AddMoveListener implements ActionListener

Example2_8 lis;
public AddMoveListener(Example2_8 lis)

this.lis = lis;

public void actionPerformed(ActionEvent e)

button. _________(lis);
stopButton, setEnabled (true);


class RemoveListener implements ActionListener

Example2_8 lis;
public RemoveListener(Example2_8 lis)

this.lis = lis;

public void actionPerformed(ActionEvent e)

button, removeKeyListener (lis);
stopButton.setEnabled(false);



Example2_8. html
<HTML>
<HEAD>
<TITLE> Example2_8</TITLE>
</HEAD>
<BODY>
<APPLET CODE="Example2_8.class"WIDTH=400 HEIGHT=500>
</APPLET>
</BODY>
</HTML>

答案

参考答案:init
addKeyListener

解析: 本题考查知识点:小应用程序概念、Applet执行过程、JavaApplication和Applet。解题思路:Applet运行时,首先由浏览器调用init方法,该方法通知Applet已被加载,在这个方法中通常进行一些基本的初始化过程。Applet的基本方法还有start()、stop()、destroy()。类Example2_8实现了“KeyListener”监听器接口,就可以通过该监听器的方法监听键盘事件。需要填空的方法是初始化Applet程序,keyPressed()方法中专门处理方向键的事件。按下方向键以后,就会调用Label的setLocation()方法重新设置“out”所在的位置。当用户按下“移动”按钮以后,AddMoveListener为“移动按钮”添加了针对键盘的监听器。当用户按下“停止移动”按钮以后,RemoveListener从“移动”按钮中移出针对键盘事件的监听器。
本题中start方法已经实现,另外两个方法分别用于Applet的停止和卸载,所以第一个空只能填“init”,用来为Applet实现初始化。
由于本题是使用键盘来控制Label对象的移动,所以必须添加针对键盘的监听器,这样才能对键盘事’件做出反应,第二个空就是给“button”添加键盘事件监听器。

问答题 简答题
单项选择题 案例分析题