java swing应用(2):事件处理

来源:互联网 发布:linux设置开机启动程序 编辑:程序博客网 时间:2024/06/04 19:18
一个按钮的事件处理
import javax.swing.*;import java.awt.event.*;//实现ActionListenerpublic class GuiDemo2 implements ActionListener{  JButton button;  public static void main(String[] args){      GuiDemo2 gui = new GuiDemo2();      gui.go();  }  public void go(){      //创建面板JFrame      JFrame frame = new JFrame();      //窗口关闭退出应该程序      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);      //创建 按钮      button = new JButton("按钮A");      //按钮监听      button.addActionListener(this);      //面板添加按钮      frame.getContentPane().add(button);      //设置大小、可见      frame.setSize(300,300);      frame.setVisible(true);  }  //实现接口上的方法  public void actionPerformed(ActionEvent event){      button.setText("按钮A被点击了");  }}
多个按钮的事件处理
import java.awt.*;  import javax.swing.*;import java.awt.event.*;public class GuiDemo3{    JButton button1;  JButton button2;  public static void main(String[] args){      GuiDemo3 gui = new GuiDemo3();      gui.go();  }  public void go(){      //创建面板JFrame      JFrame frame = new JFrame();      //窗口关闭退出应该程序      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);      //创建 按钮      button1 = new JButton("按钮A");      button2 = new JButton("按钮B");      //按钮监听      button1.addActionListener(new Button1Listener());      button2.addActionListener(new Button2Listener());      //面板添加按钮(BorderLayout.SOUTH、CENTER、EAST、WEST、NORTH)      frame.getContentPane().add(BorderLayout.SOUTH, button1);//默认区域南      frame.getContentPane().add(BorderLayout.NORTH, button2);      //设置大小、可见      frame.setSize(300,300);      frame.setVisible(true);  }  //内部类,实现ActionListener  class Button1Listener implements ActionListener{      public void actionPerformed(ActionEvent event){          button1.setText("按钮A被点击了");      }  }  //内部类,实现ActionListener  class Button2Listener implements ActionListener{      public void actionPerformed(ActionEvent event){          button2.setText("按钮B被点击了");      }  }}