JavaSE系列代码48:命令按钮功能的实现

We can also extend the exception class to define our own exception class, and then specify which methods generate such exceptions. When a method is declared, it can use the throws keyword to declare and throw a number of exceptions to be generated. In the method body of the method, the operation to generate the exception is specified, that is, to create an object with the corresponding exception class, which will cause the method to end execution and throw the created exception object. The program must invoke the method of throwing exceptions in the try~catch block statement.

import java.awt.*; 
import java.awt.event.*;
public class Javase_48 extends Frame implements ActionListener
{
  static app13_3 frm=new app13_3();
  static Panel pan1=new Panel();
  static Panel pan2=new Panel();
  static Button but1= new Button("第一页");
  static Button but2= new Button("上一页");
  static Button but3= new Button("下一页");
  static Button but4= new Button("最后页");
  static CardLayout crd=new CardLayout (5,10);  //需将crd定义为static类型
  public static void main(String[] args)
  {
    frm.setLayout(null);
    frm.setTitle("操作事件");
    pan2.setLayout(new GridLayout(1,4)); 
    pan1.setLayout(crd);
    frm.setSize(300,250);
    frm.setResizable(false);
    but1.addActionListener(frm);      //把事件监听者frm向but1注册
    but2.addActionListener(frm);      //把事件监听者frm向but2注册
    but3.addActionListener(frm);      //把事件监听者frm向but3注册
    but4.addActionListener(frm);      //把事件监听者frm向but4注册
    pan1.setBounds(10,20,270,200);
    pan2.setBounds(10,220,270, 20);
    frm.add(pan1); 
    frm.add(pan2) ;
    Label lab1=new Label("第一页", Label.CENTER);
    TextField tex=new TextField("卡片式布局策略CardLayout",18);
    pan1.add(lab1, "n1");
    pan1.add(new Label("第二页", Label.CENTER), "n2");
    pan1.add(tex, "n3");
    crd.show(pan1, "n3");
    pan2.add(but1, "d1");
    pan2.add(but2, "d2");
    pan2.add(but3, "d3");
    pan2.add(but4, "d4");
    frm.setVisible(true);
  }
  public void actionPerformed(ActionEvent e)
  {
    Button but=(Button)e.getSource();    //获得事件源并强制将其转换成Button类型
    if(but==but1) crd.first(pan1);        //单击的是but1按钮,则显示第一张卡片
    else if(but==but2) crd.previous(pan1);
    else if(but==but3) crd.next(pan1);
    else crd.last(pan1);
  }
}

发布了52 篇原创文章 · 获赞 162 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/blog_programb/article/details/105394945