控制台程序。

定义监听器类有许多方式。下面把监听器类定义为单独的类MouseHandler:

 // Mouse event handler for a selection button
import java.awt.Cursor;
import java.awt.event.*; public class MouseHandler extends MouseAdapter {
Cursor handCursor = new Cursor(Cursor.HAND_CURSOR);
Cursor defaultCursor = new Cursor(Cursor.DEFAULT_CURSOR); // Handle mouse entering the selection button
@Override
public void mouseEntered(MouseEvent e) {
e.getComponent().setCursor(handCursor); // Switch to hand cursor
}
// Handle mouse exiting the selection button
@Override
public void mouseExited(MouseEvent e) {
e.getComponent().setCursor(defaultCursor); // Change to default cursor
}
}

然后修改createGUI()方法中的循环,为applet添加鼠标监听器即可:

 // Applet to generate lottery entries
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.Random; // For random number generator @SuppressWarnings("serial")
public class Lottery extends JApplet {
// Generate NUMBER_COUNT random selections from the VALUES array
private static int[] getNumbers() {
int[] numbers = new int[NUMBER_COUNT]; // Store for the numbers to be returned
int candidate = 0; // Stores a candidate selection
for(int i = 0; i < NUMBER_COUNT; ++i) { // Loop to find the selections search:
// Loop to find a new selection different from any found so far
while(true) {
candidate = VALUES[choice.nextInt(VALUES.length)];
for(int j = 0 ; j < i ; ++j) { // Check against existing selections
if(candidate==numbers[j]) { // If it is the same
continue search; // get another random selection
}
}
numbers[i] = candidate; // Store the selection in numbers array
break; // and go to find the next
}
}
return numbers; // Return the selections
} // Initialize the applet
@Override
public void init() {
SwingUtilities.invokeLater( // Create interface components
new Runnable() { // on the event dispatching thread
public void run() {
createGUI();
}
});
} // Create User Interface for applet
public void createGUI() {
// Set up the selection buttons
Container content = getContentPane();
content.setLayout(new GridLayout(0,1)); // Set the layout for the applet // Set up the panel to hold the lucky number buttons
JPanel buttonPane = new JPanel(); // Add the pane containing numbers // Let's have a fancy panel border
buttonPane.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(Color.cyan,
Color.blue),
"Every One a Winner!")); int[] choices = getNumbers(); // Get initial set of numbers
MouseHandler mouseHandler = new MouseHandler(); // Create the listener
for(int i = 0 ; i < NUMBER_COUNT ; ++i) {
luckyNumbers[i] = new Selection(choices[i]);
luckyNumbers[i].addActionListener(luckyNumbers[i]); // Button is it's own listener
luckyNumbers[i].addMouseListener(mouseHandler);
buttonPane.add(luckyNumbers[i]);
}
content.add(buttonPane); // Add the pane containing control buttons
JPanel controlPane = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 10)); // Add the two control buttons
JButton button; // A button variable
Dimension buttonSize = new Dimension(100,20); // Button size controlPane.add(button = new JButton("Lucky Numbers!"));
button.setBorder(BorderFactory.createRaisedBevelBorder());
button.addActionListener(new HandleControlButton(PICK_LUCKY_NUMBERS));
button.setPreferredSize(buttonSize); controlPane.add(button = new JButton("Color"));
button.setBorder(BorderFactory.createRaisedBevelBorder());
button.addActionListener(new HandleControlButton(COLOR));
button.setPreferredSize(buttonSize); content.add(controlPane);
} // Class defining custom buttons showing lottery selection
private class Selection extends JButton implements ActionListener {
// Constructor
public Selection(int value) {
super(Integer.toString(value)); // Call base constructor and set the label
this.value = value; // Save the value
setBackground(startColor);
setBorder(BorderFactory.createRaisedBevelBorder()); // Add button border
setPreferredSize(new Dimension(80,20));
} // Handle selection button event
public void actionPerformed(ActionEvent e) {
// Change this selection to a new selection
int candidate = 0;
while(true) { // Loop to find a different selection
candidate = VALUES[choice.nextInt(VALUES.length)];
if(!isCurrentSelection(candidate)) { // If it is different
break; // end the loop
}
}
setValue(candidate); // We have one so set the button value
}
// Set the value for the selection
public void setValue(int value) {
setText(Integer.toString(value)); // Set value as the button label
this.value = value; // Save the value
} // Check the value for the selection
boolean hasValue(int possible) {
return value==possible; // Return true if equals current value
} // Check the current choices
boolean isCurrentSelection(int possible) {
for(int i = 0 ; i < NUMBER_COUNT ; ++i) { // For each button
if(luckyNumbers[i].hasValue(possible)) { // check against possible
return true; // Return true for any =
}
}
return false; // Otherwise return false
} private int value; // Value for the selection button
} // Class defining a handler for a control button
private class HandleControlButton implements ActionListener {
// Constructor
public HandleControlButton(int buttonID) {
this.buttonID = buttonID; // Store the button ID
} // Handle button click
public void actionPerformed(ActionEvent e) {
switch(buttonID) {
case PICK_LUCKY_NUMBERS:
int[] numbers = getNumbers(); // Get maxCount random numbers
for(int i = 0 ; i < NUMBER_COUNT ; ++i) {
luckyNumbers[i].setValue(numbers[i]); // Set the button VALUES
}
break;
case COLOR:
Color color = new Color(
flipColor.getRGB()^luckyNumbers[0].getBackground().getRGB());
for(int i = 0 ; i < NUMBER_COUNT ; ++i)
luckyNumbers[i].setBackground(color); // Set the button colors
break;
}
} private int buttonID;
} final static int NUMBER_COUNT = 6; // Number of lucky numbers
final static int MIN_VALUE = 1; // Minimum in range
final static int MAX_VALUE = 49; // Maximum in range
final static int[] VALUES = new int[MAX_VALUE-MIN_VALUE+1]; // Array of possible VALUES
static { // Initialize array
for(int i = 0 ; i < VALUES.length ; ++i)
VALUES[i] = i + MIN_VALUE;
} // An array of custom buttons for the selected numbers
private Selection[] luckyNumbers = new Selection[NUMBER_COUNT];
final public static int PICK_LUCKY_NUMBERS = 1; // Select button ID
final public static int COLOR = 2; // Color button ID // swap colors
Color flipColor = new Color(Color.YELLOW.getRGB()^Color.RED.getRGB()); Color startColor = Color.YELLOW; // start color private static Random choice = new Random(); // Random number generator
}

Html文件和上一个例子一样。

对于鼠标是动作源的任何组件来说,都可以应用上述技巧。

Java基础之处理事件——选项按钮的鼠标监听器(Lottery 2 with mouse listener)的更多相关文章

  1. Java基础之处理事件——添加工具栏(Sketcher 7 with File toolbar buttons)

    控制台程序. 工具栏在应用程序窗口中通常位于内容面板顶部的菜单栏下,包含直接访问菜单选项的按钮.在Sketcher程序中可以为最常用的菜单项添加工具栏. 工具栏是javax.swing.JToolBa ...

  2. Java基础之处理事件——实现低级事件监听器(Sketcher 2 implementing a low-level listener)

    控制台程序. 定义事件监听器的类必须实现监听器接口.所有的事件监听器接口都扩展了java.util.EventListener接口.这个接口没有声明任何方法,仅仅用于表示监听器对象.使用EventLi ...

  3. Java基础之处理事件——使用动作Action(Sketcher 6 using Action objects)

    控制台程序. 动作Action是任何实现了javax.swing.Action接口的类的对象.这个接口声明了操作Action对象的方法,例如,存储与动作相关的属性.启用和禁用动作.Action接口扩展 ...

  4. Java基础之处理事件——应用程序中的语义事件监听器(Sketcher 5 with element color listeners)

    控制台程序. 为了标识元素的类型,可以为菜单已提供的4中元素定义常量,用作ID.这有助于执行菜单项监听器的操作,还提供了一种标识颜色类型的方式.我们会累积许多应用程序范围的常量,所以把它们定义为可以静 ...

  5. Java基础之处理事件——applet中语义事件的处理(Lottery 1)

    控制台程序. 语义事件与程序GUI上的组件操作有关.例如,如果选择菜单项或单击按钮,就会生成语义事件. 对组件执行操作时,例如选择菜单项或单击按钮,就会生成ActionEvent事件.在选择或取消选择 ...

  6. Java基础之处理事件——使窗口处理自己的事件(Skethcer 1 handing its own closing event)

    控制台程序. 为表示事件的常量使用标识符可以直接启用组件对象的特定事件组.调用组件的enableEvent()方法,并把想要启用事件的标识符传送为参数,但这只在不使用监视器的情况下有效.注册监听器会自 ...

  7. Java基础之处理事件——添加工具提示(Sketcher 9 with tooltips)

    控制台程序. 在Java中实现对工具提示的支持是非常简单的,秘诀仍在我们一直使用的Action对象中.Action对象拥有存储工具提示文本的内置功能因为文本是通过SHORT_DESCRIPTION键提 ...

  8. Java基础之处理事件——添加菜单图标(Sketcher 8 with toolbar buttons and menu icons)

    控制台程序. 要为菜单项添加图标以补充工具栏图标,只需要在创建菜单项的Action对象中添加IconImage对象,作为SMALL_ICON键的值即可. // Defines application ...

  9. Java基础之处理事件——使用适配器类(Sketcher 3 using an Adapter class)

    控制台程序. 适配器类是指实现了监听器接口的类,但监听器接口中的方法没有内容,所以它们什么也不做.背后的思想是:允许从提供的适配器类派生自己的监听器类,之后再实现那些自己感兴趣的类.其他的空方法会从适 ...

随机推荐

  1. 判断返回数据是否为 null

    判断是否为null //尖括号                if ([regeocode.city isEqual:[NSNull class]]) {                    NSL ...

  2. 用命令行导出和导入MySQL数据库

    php 用命令行导出和导入MySQL数据库   命令行导出数据库:1,进入MySQL目录下的bin文件夹:cd MySQL中到bin文件夹的目录如我输入的命令行:cd C:\Program Files ...

  3. php数据库两个关联大表的大数组分页处理,防止内存溢出

    $ret = self::$db->select($tables, $fields, $where, $bind); if (!empty($ret)) { $retIds = array(); ...

  4. 【转】UGUI实现unity摇杆

    http://blog.csdn.net/onafioo/article/details/46403801 http://www.winig.cc/archives/348 好久没有写文章了,最近在做 ...

  5. 【转】下载量最高的 100 个 Laravel 扩展包推荐

    说明 Laravel 另一个令人喜欢的地方,是拥有活跃的开发者社区,而活跃的开发者社区带来的,是繁华的扩展包生态. 本文对 Packagist 上打了 Laravel 标签 的扩展包进行整理,截止到现 ...

  6. 【git】删除某个文件的所有历史记录,批量删除远程分支

    删除git某个文件的所有历史记录 git的目的就是版本控制,记录每一个版本的变动.然而有的时候我们往往希望从版本库中彻底删除某个文件,不再显示在历史记录中.例如不小心上传了一堆错误的文件,或者不小心上 ...

  7. java笔记--关于线程同步(5种同步方式)【转】

    为何要使用同步?     java允许多线程并发控制,当多个线程同时操作一个可共享的资源变量时(如数据的增删改查),      将会导致数据不准确,相互之间产生冲突,因此加入同步锁以避免在该线程没有完 ...

  8. JavaScript判断字符串的字符长度(中文占两个字符)

    判断方法 //判断字符串中的字符 中文算两个字符 function chkstrlen(str) { ; ; i < str.length; i++) { ) //如果是汉字,则字符串长度加2 ...

  9. C# Json时间类型的转换

    DateTime dt1 = new DateTime(1970, 1, 1); dt1 = dt1.AddMilliseconds(long.Parse(list.Items[i].UpdatedA ...

  10. AOP 底层技术比较

    表 1. AOP 底层技术比较 AOP 底层技术 功能 性能 面向接口编程 编程难度 直接改写 class 文件 完全控制类 无明显性能代价 不要求 高,要求对 class 文件结构和 Java 字节 ...