码迷,mamicode.com
首页 > 编程语言 > 详细

【JAVA语言程序设计基础篇】--事件驱动程序设计--setActionCommand()

时间:2016-08-17 16:48:04      阅读:431      评论:0      收藏:0      [点我收藏+]

标签:



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);
			
		}
	}
}


技术分享技术分享


【JAVA语言程序设计基础篇】--事件驱动程序设计--setActionCommand()

标签:

原文地址:http://blog.csdn.net/qq_24653023/article/details/52231934

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!