⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 actionlistenerframe.java

📁 Eclipse程序设计经典教程+源代码 学习java的朋友可以看看
💻 JAVA
字号:
package listener;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class ActionListenerFrame extends JFrame implements ActionListener {
  private JPanel contentPane;
  BorderLayout borderLayout1 = new BorderLayout();
  JButton jButton1 = new JButton();
  JButton jButton2 = new JButton();
  JButton jButton3 = new JButton();
  JButton jButton4 = new JButton();
  JButton jButton5 = new JButton();

  public static void main(String[] args) {
    ActionListenerFrame frame = new ActionListenerFrame();
    Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
    Dimension frameSize = frame.getSize();
    frame.setLocation( (screenSize.width - frameSize.width) / 2,
                      (screenSize.height - frameSize.height) / 2);
    frame.setVisible(true);
  }

  public ActionListenerFrame() {
    try {
      //窗口关闭时清空内存
      setDefaultCloseOperation(EXIT_ON_CLOSE);
      jbInit();
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }

  private void jbInit() throws Exception  {
    contentPane = (JPanel) this.getContentPane();
    contentPane.setLayout(borderLayout1);
    this.setSize(new Dimension(400, 300));
    this.setTitle("ActionListener动作接收器示例");
    //设置按钮的文字属性
    jButton1.setText("北");
    //设置按钮的动作字符串属性
    jButton1.setActionCommand("north");
    //为按钮加入动作接收器
    jButton1.addActionListener(this);
    jButton2.setText("西");
    jButton2.setActionCommand("west");
    jButton2.addActionListener(this);
    jButton3.setText("中");
    jButton3.setActionCommand("center");
    jButton3.addActionListener(this);
    jButton4.setText("东");
    jButton4.setActionCommand("east");
    jButton4.addActionListener(this);
    jButton5.setText("南");
    jButton5.setActionCommand("south");
    jButton5.addActionListener(this);
    //为面板加入按钮
    contentPane.add(jButton1,  BorderLayout.NORTH);
    contentPane.add(jButton2, BorderLayout.WEST);
    contentPane.add(jButton3, BorderLayout.CENTER);
    contentPane.add(jButton4, BorderLayout.EAST);
    contentPane.add(jButton5, BorderLayout.SOUTH);
  }

  //单击事件的处理代码
  public void actionPerformed(ActionEvent e) {
    //取得按钮的动作字符串
    String actionCommand = e.getActionCommand().trim();
    //单击按钮的处理代码
    if (actionCommand.equals("north")) {
      JOptionPane.showMessageDialog(null, "北面按钮被单击");
    }else if(actionCommand.equals("west")){
      JOptionPane.showMessageDialog(null, "西面按钮被单击");
    }else if(actionCommand.equals("center")){
      JOptionPane.showMessageDialog(null, "中间按钮被单击");
    }else if(actionCommand.equals("east")){
      JOptionPane.showMessageDialog(null, "东面按钮被单击");
    }else if(actionCommand.equals("south")){
      JOptionPane.showMessageDialog(null, "南面按钮被单击");
    }
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -