下面是一个Applet程序,其功能是实现对JButton类的扩展,封装成上网助力一样的按钮类,每个按钮对象对应一个 URL地址,点击则访问相应的URL。要求在窗口中从上到下排列3个这样的按钮。请改正程序中的错误(有下划线的语句),使程序能输出正确的结果。

admin2009-01-15  22

问题 下面是一个Applet程序,其功能是实现对JButton类的扩展,封装成上网助力一样的按钮类,每个按钮对象对应一个 URL地址,点击则访问相应的URL。要求在窗口中从上到下排列3个这样的按钮。请改正程序中的错误(有下划线的语句),使程序能输出正确的结果。
   注意:不改动程序的结构,不得增行或删行。
   程序运行结果如下:
   
   import java.net.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   public class ex28_3 extends JApplet implements ActionListener {
      ButtonURL[] btnURL = new ButtonURL[3];
      public void init()  {
         btnURL[0] = new ButtonURL("新浪网","http://www.sina.com.cn/");
         btnURL[1] = new ButtonURL("163","http://www.163.com/");
         btnURL[2] = new ButtonURL("搜狐","http://www.sohu.com/");
         GridLayout gl = new GridLayout(1,3);
         getContentPane().setLayout(gl);
         for (int i = 0; i < btnURL.length; i++)  {
            btnURL.addActionListener(this);
            getContentPane().add(btnURL);
         }
     }
     public void actionPerformed(ActionEvent ae)  {
        ButtonURL btnClick =ae.getSource();//获取发生事件的对象
        try {
           URL load = new URL(btnClick.strAddr);
           getAppletContext().showDocument(strAddr);
        } catch (MalformedURLException e)  {
           showStatus("Bad URL:" + btnClick.strAddr);
        }
    }
  }
  class ButtonURL extends JButton {
     String strAddr;
     ButtonURL(String strLabel,  String strAddress)  {
        super(strLabel);
        strAddr = strAddress;
     }
  }
ex28_3, html
<HTML>
<HEAD>
   <TITLE>ex28_3</TITLE>
</HEAD>
<BODY>
<applet code="ex28_3.class" width=800 height=400 >
</applet>
</BODY>
</HTML>

选项

答案 new GridLayout(3,1) (ButtonURL)ae.getSource() showDocument(load)

解析 本题主要考查面向对象的基本程序设计思想和Applet事件处理机制及Applet和Application相结合的程序设计。解题关键是熟悉swing的基本构件,并会根据需要进行扩展,这里的ButtonURL类就是对JButton类的扩展,熟悉布局的基本操作等。本题中,第1处,按题目要求,应该是纵向排列的3个按钮;第2处,ae对象调用getSource()方返回的是JButton类的对象,这里需要ButtonURL的对象,所以需要进行转换;第3处,参数错误,应该是对象btnClick的成员变量strAddr的值。
转载请注明原文地址:https://kaotiyun.com/show/fHnp777K
0

相关试题推荐
最新回复(0)