setActionCommand()和getActionCommand()的使用
/** * 功能:事件处理机制 * */ package com.test3; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Graphics; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; @SuppressWarnings("serial") public class Demo9_3 extends JFrame{ MyPanel p1 = new MyPanel(); JButton button1 = new JButton("黑色"); JButton button2 = new JButton("红色"); public Demo9_3(){ add(button1,BorderLayout.NORTH); add(button2,BorderLayout.SOUTH); add(p1); p1.setBackground(Color.black); button1.addActionListener(new ActionListener(){//匿名內部类 @Override public void actionPerformed(ActionEvent e) { p1.setBackground(Color.black); repaint(); } }); button2.addActionListener(new ActionListener() {//匿名内部类 @Override public void actionPerformed(ActionEvent e) { if(e.getActionCommand().equals("red")){//51行setActionCommand方法中 的字符串如果等于 该行equal()中的字符串 就handle it p1.setBackground(Color.red); System.out.println("getActionCommand method is uesd successful"); } repaint(); } }); button2.setActionCommand("red"); setSize(400, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public static void main(String[] args) { new Demo9_3(); } class MyPanel extends JPanel{ public void paintComponent(Graphics g){ super.paintComponent(g); } } }
时间: 2024-11-09 03:22:04