May 08

The InputEvent’s modifiers property is a mask and a bitwise AND can be used to check what is set and what isn’t. The following utility method demonstrates how to check what modifiers are set in the mask and return a string representation.

import static java.awt.event.InputEvent.*;
import java.awt.event.InputEvent;
 
 
public class EventUtils {
 
    public static String eventModifiersToString(InputEvent e) {
        int modifiers = e.getModifiers();
        StringBuilder sb = new StringBuilder();
        for (int i = SHIFT_MASK; i <= ALT_GRAPH_DOWN_MASK; i <<= 1) {
            int and = modifiers & i;
			if (and == SHIFT_MASK) 
				sb.append("SHIFT_MASK ");
			else if (and == CTRL_MASK) 
            	sb.append("CTRL_MASK ");
			else if (and == BUTTON3_MASK) 
				sb.append("BUTTON3_MASK ");
			else if (and == META_MASK) 
				sb.append("META_MASK ");
			else if (and == ALT_MASK) 
				sb.append("ALT_MASK ");
			else if (and == BUTTON2_MASK) 
				sb.append("BUTTON2_MASK ");
			else if (and == BUTTON1_MASK) 
				sb.append("BUTTON1_MASK ");
			else if (and == ALT_GRAPH_MASK) 
				sb.append("ALT_GRAPH_MASK ");
			else if (and == SHIFT_DOWN_MASK) 
				sb.append("SHIFT_DOWN_MASK ");
			else if (and == CTRL_DOWN_MASK) 
				sb.append("CTRL_DOWN_MASK ");
			else if (and == META_DOWN_MASK) 
				sb.append("META_DOWN_MASK ");
			else if (and == ALT_DOWN_MASK) 
				sb.append("ALT_DOWN_MASK ");
			else if (and == BUTTON1_DOWN_MASK) 
				sb.append("BUTTON1_DOWN_MASK ");
			else if (and == BUTTON2_DOWN_MASK) 
				sb.append("BUTTON2_DOWN_MASK ");
			else if (and == BUTTON3_DOWN_MASK) 
				sb.append("BUTTON3_DOWN_MASK ");
			else if (and == ALT_GRAPH_DOWN_MASK) 
				sb.append("ALT_GRAPH_DOWN_MASK ");
        }
        return sb.toString().trim();
    }
}

written by objects \\ tags: , , , ,