java点击按钮改变颜色_Java 按钮和单击事件映射到动作对象改变面板颜色小程序实例 Java核心技术 事件处理...

Java 按钮和单击事件映射到动作对象改变面板颜色小程序实例 Java核心技术 事件处理

source code:

package com.sunnyykn.chapter08;

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

/**

* A panel with buttons and keyboard shortcuts to change

* the background color.

* @author sunnyykn

*/

class ActionPanel extends JPanel

{

public ActionPanel()

{

//define actions

Action yellowAction = new ColorAction("Yellow",

new ImageIcon("yellow-ball.gif"),

Color.YELLOW);

Action blueAction = new ColorAction("Blue",

new ImageIcon("blue-ball.gif"),

Color.BLUE);

Action redAction = new ColorAction("Red",

new ImageIcon("red-ball.gif"),

Color.RED);

//add buttons for these actions

add(new JButton(yellowAction));

add(new JButton(blueAction));

add(new JButton(redAction));

//associate the Y,B,and R keys with names

InputMap imap = getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);

imap.put(KeyStroke.getKeyStroke("ctrl Y"),"panel.yellow");

imap.put(KeyStroke.getKeyStroke("ctrl B"),"panel.blue");

imap.put(KeyStroke.getKeyStroke("ctrl R"),"panel.red");

//associate the names with actions

ActionMap amap = getActionMap();

amap.put("panel.yellow", yellowAction);

amap.put("panel.blue", blueAction);

amap.put("panel.red", redAction);

}

public class ColorAction extends AbstractAction

{

/**

* Constructs a color action.

* @param name the name to show on the button

* @param icon the icon to display on the button

* @param c the background color

*/

public ColorAction(String name,Icon icon,Color c)

{

putValue(Action.NAME,name);

putValue(Action.SMALL_ICON,icon);

putValue(Action.SHORT_DESCRIPTION,"Set panel color to " + name.toLowerCase());

putValue("color",c);

}

public void actionPerformed(ActionEvent event)

{

Color c = (Color) getValue("color");

setBackground(c);

}

}

}

/**

* A frame with a panel that demonstrates color change actions.

* @author sunnyykn

*

*/

class ActionFrame extends JFrame

{

public static final int DEFAULT_WIDTH = 300;

public static final int DEFAULT_HEIGHT = 200;

public ActionFrame()

{

setTitle("ActionTest Sunnyykn");

setSize(DEFAULT_WIDTH,DEFAULT_HEIGHT);

//add panel to frame

ActionPanel panel = new ActionPanel();

add(panel);

}

}

public class ActionTest {

public static void main(String args[])

{

ActionFrame frame = new ActionFrame();

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.setVisible(true);

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值