• Java基础之处理事件——选项按钮的鼠标监听器(Lottery 2 with mouse listener)


    控制台程序。

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

     1 // Mouse event handler for a selection button
     2 import java.awt.Cursor;
     3 import java.awt.event.*;
     4 
     5 public class MouseHandler extends MouseAdapter {
     6   Cursor handCursor = new Cursor(Cursor.HAND_CURSOR);
     7   Cursor defaultCursor = new Cursor(Cursor.DEFAULT_CURSOR);
     8 
     9   // Handle mouse entering the selection button
    10   @Override
    11   public void mouseEntered(MouseEvent e) {
    12     e.getComponent().setCursor(handCursor);                            // Switch to hand cursor
    13   }
    14   // Handle mouse exiting the selection button
    15   @Override
    16   public void mouseExited(MouseEvent e) {
    17     e.getComponent().setCursor(defaultCursor);                         // Change to default cursor
    18   }
    19 }

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

      1 // Applet to generate lottery entries
      2 import javax.swing.*;
      3 import java.awt.*;
      4 import java.awt.event.*;
      5 import java.util.Random;               // For random number generator
      6 
      7 @SuppressWarnings("serial")
      8 public class Lottery extends JApplet {
      9   // Generate NUMBER_COUNT random selections from the VALUES array
     10   private static int[] getNumbers() {
     11     int[] numbers = new int[NUMBER_COUNT];                             // Store for the numbers to be returned
     12     int candidate = 0;                                                 // Stores a candidate selection
     13     for(int i = 0; i < NUMBER_COUNT; ++i) {                            // Loop to find the selections
     14 
     15       search:
     16       // Loop to find a new selection different from any found so far
     17       while(true) {
     18         candidate = VALUES[choice.nextInt(VALUES.length)];
     19         for(int j = 0 ; j < i ; ++j) {                                 // Check against existing selections
     20           if(candidate==numbers[j]) {                                  // If it is the same
     21             continue search;                                           // get another random selection
     22           }
     23         }
     24         numbers[i] = candidate;                                        // Store the selection in numbers array
     25         break;                                                         // and go to find the next
     26       }
     27     }
     28     return numbers;                                                    // Return the selections
     29   }
     30 
     31   // Initialize the applet
     32   @Override
     33   public void init() {
     34     SwingUtilities.invokeLater(                                        // Create interface components
     35       new Runnable() {                                                 // on the event dispatching thread
     36         public void run() {
     37           createGUI();
     38         }
     39     });
     40   }
     41 
     42   // Create User Interface for applet
     43   public void createGUI() {
     44     // Set up the selection buttons
     45     Container content = getContentPane();
     46     content.setLayout(new GridLayout(0,1));                            // Set the layout for the applet
     47 
     48     // Set up the panel to hold the lucky number buttons
     49     JPanel buttonPane = new JPanel();                                  // Add the pane containing numbers
     50 
     51     // Let's have a fancy panel border
     52     buttonPane.setBorder(BorderFactory.createTitledBorder(
     53                          BorderFactory.createEtchedBorder(Color.cyan,
     54                                                           Color.blue),
     55                                                           "Every One a Winner!"));
     56 
     57     int[] choices = getNumbers();                                      // Get initial set of numbers
     58     MouseHandler mouseHandler = new MouseHandler();                    // Create the listener
     59     for(int i = 0 ; i < NUMBER_COUNT ; ++i) {
     60       luckyNumbers[i] = new Selection(choices[i]);
     61       luckyNumbers[i].addActionListener(luckyNumbers[i]);               // Button is it's own listener
     62       luckyNumbers[i].addMouseListener(mouseHandler);
     63       buttonPane.add(luckyNumbers[i]);
     64     }
     65     content.add(buttonPane);
     66 
     67     // Add the pane containing control buttons
     68    JPanel controlPane = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 10));
     69 
     70     // Add the two control buttons
     71     JButton button;                                                    // A button variable
     72     Dimension buttonSize = new Dimension(100,20);                      // Button size
     73 
     74     controlPane.add(button = new JButton("Lucky Numbers!"));
     75     button.setBorder(BorderFactory.createRaisedBevelBorder());
     76     button.addActionListener(new HandleControlButton(PICK_LUCKY_NUMBERS));
     77     button.setPreferredSize(buttonSize);
     78 
     79     controlPane.add(button = new JButton("Color"));
     80     button.setBorder(BorderFactory.createRaisedBevelBorder());
     81     button.addActionListener(new HandleControlButton(COLOR));
     82     button.setPreferredSize(buttonSize);
     83 
     84     content.add(controlPane);
     85   }
     86 
     87   // Class defining custom buttons showing lottery selection
     88   private class Selection extends JButton implements ActionListener {
     89     // Constructor
     90     public Selection(int value) {
     91       super(Integer.toString(value));                                  // Call base constructor and set the label
     92       this.value = value;                                              // Save the value
     93       setBackground(startColor);
     94       setBorder(BorderFactory.createRaisedBevelBorder());              // Add button border
     95       setPreferredSize(new Dimension(80,20));
     96     }
     97 
     98     // Handle selection button event
     99     public void actionPerformed(ActionEvent e) {
    100       // Change this selection to a new selection
    101       int candidate = 0;
    102       while(true) {                                                    // Loop to find a different selection
    103         candidate = VALUES[choice.nextInt(VALUES.length)];
    104         if(!isCurrentSelection(candidate)) {                           // If it is different
    105           break;                                                       // end the loop
    106         }
    107       }
    108       setValue(candidate);                                             // We have one so set the button value
    109     }
    110     // Set the value for the selection
    111     public void setValue(int value) {
    112       setText(Integer.toString(value));                                // Set value as the button label
    113       this.value = value;                                              // Save the value
    114     }
    115 
    116     // Check the value for the selection
    117     boolean hasValue(int possible) {
    118       return value==possible;                                          // Return true if equals current value
    119     }
    120 
    121     // Check the current choices
    122     boolean isCurrentSelection(int possible) {
    123       for(int i = 0 ; i < NUMBER_COUNT ; ++i) {                        // For each button
    124         if(luckyNumbers[i].hasValue(possible)) {                       // check against possible
    125           return true;                                                 // Return true for any =
    126         }
    127       }
    128       return false;                                                    // Otherwise return false
    129     }
    130 
    131     private int value;                                                 // Value for the selection button
    132   }
    133 
    134   // Class defining a handler for a control button
    135   private class HandleControlButton implements ActionListener {
    136     // Constructor
    137     public HandleControlButton(int buttonID) {
    138       this.buttonID = buttonID;                                        // Store the button ID
    139     }
    140 
    141     // Handle button click
    142     public void actionPerformed(ActionEvent e) {
    143       switch(buttonID) {
    144         case PICK_LUCKY_NUMBERS:
    145           int[] numbers = getNumbers();                                // Get maxCount random numbers
    146           for(int i = 0 ; i < NUMBER_COUNT ; ++i) {
    147             luckyNumbers[i].setValue(numbers[i]);                      // Set the button VALUES
    148           }
    149           break;
    150         case COLOR:
    151           Color color = new Color(
    152                 flipColor.getRGB()^luckyNumbers[0].getBackground().getRGB());
    153           for(int i = 0 ; i < NUMBER_COUNT ; ++i)
    154             luckyNumbers[i].setBackground(color);                      // Set the button colors
    155           break;
    156       }
    157     }
    158 
    159     private int buttonID;
    160   }
    161 
    162   final static int NUMBER_COUNT = 6;                                   // Number of lucky numbers
    163   final static int MIN_VALUE = 1;                                      // Minimum in range
    164   final static int MAX_VALUE = 49;                                     // Maximum in range
    165   final static int[] VALUES = new int[MAX_VALUE-MIN_VALUE+1];          // Array of possible VALUES
    166   static {                                                             // Initialize array
    167     for(int i = 0 ; i < VALUES.length ; ++i)
    168       VALUES[i] = i + MIN_VALUE;
    169   }
    170 
    171   // An array of custom buttons for the selected numbers
    172   private Selection[] luckyNumbers = new Selection[NUMBER_COUNT];
    173   final public static int PICK_LUCKY_NUMBERS = 1;                      // Select button ID
    174   final public static int COLOR = 2;                                   // Color button ID
    175 
    176   // swap colors
    177   Color flipColor = new Color(Color.YELLOW.getRGB()^Color.RED.getRGB());
    178 
    179   Color startColor = Color.YELLOW;                                     // start color
    180 
    181   private static Random choice = new Random();                         // Random number generator
    182 }

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

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

  • 相关阅读:
    Mysql 之导入导出
    Go gin之文件上传
    记录Go gin集成发送邮件接口的坑
    关于mysql某个用户无法登陆的情况
    面向对象程序设计的分析基本步骤
    提示框判断事件
    事件响应的公共方法
    IComparable<T>.CompareTo(T) 方法
    浏览器缓存机制
    PHP中include和require
  • 原文地址:https://www.cnblogs.com/mannixiang/p/3486164.html
Copyright © 2020-2023  润新知