下面是一个Applet程序,其功能是建立一个图形用户界面的窗口,包括一个文本显示区和一个按钮,点击按钮,可以在文本区已有的文本基础上追加显示10条“Welcome to the NCR Examination!”信息,并且文本区由滚动条控制文本的上下滚动。请改正程序中的错误(有下划线的语句),使程序能输出正确的结果。
注意:不改动程序的结构,不得增行或删行。
程序运行结果如下:
import javax.swing.* ;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="ex10_3.class"width = 800 height=400>
</applet>
*/
public class ex10_3 extends JApplet
JButton jb = new JButton("Add Text");
JTextPane itp = new JTextPane();
public void init()
jb.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
for(int i = 1;i<10;i++)
jtp.getText(jtp.setText()+"Welcome to the NCR Examination!\n");
);
Container cp = getContentPane();
cp.add(new JScrollPane(jtp));
cp.add(BorderLayout.SOUTH,jtp);
public static void main(String[]args)
ex10_3 obj10_3=new ex10_3();
String str = obj10_3.getClass().toString();
if(str.indexOf("class") != -1)
str = str.substring(6);
JFrame frm = new JFrame(str);
frm.addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent we)
System.exit(O);
);
frm.getContentPane().add(ex10_3);
frm.setSize(300, 400);
frm.setVisible(true);
ex10_3.html
<HTML>
<HEAD>
<TITLE>ex10_3</TITLE>
</HEAD>
<BODY>
<applet code="exl0_3.class" width=800 height=400 >
</applet>
</BODY>
</HTML>
参考答案:jtp.setText(jtp.getText() + " Welcome to the NCR Examination!\n")
cp.add(BorderLayout.SOUTH,jb)
frm.getContentPane().add(obj10_3)
解析:
本题主要考查Applet和swing结合进行图形用户界面设计的综合应用。解题关键是掌握swing的基本构件JTextPanel, JButton,JScrollPanel的用法,掌握BorderLayout布局管理器的使用方法,以及熟练掌握最基本的对象概念。本题中,第1处, JTextPanel的2个基本的方法,setText()和getText()的功能,熟悉这2个功能,则很容易就能将错误改正;第2处,应该是通过BorderLayout布局管理器在窗口的最下方添加一个JBuRon对象,需要清楚程序中每个对象所对应的类;第3处,应该是将类ex10_3的对象。obj10_3加入容器中,而不是把类作为参数传递给add()方法。