Java examples for Swing:Mouse Event
Returns true if the given mouse event occurred within a highlight on label.
//package com.java2s; import java.awt.FontMetrics; import java.awt.event.MouseEvent; import javax.swing.JTextField; import javax.swing.text.Highlighter; import javax.swing.text.Highlighter.Highlight; public class Main { /**//from w w w.j av a2 s .c o m * Returns true if the given mouse event occurred within a highlight h on label. */ public static boolean isInHighlight(MouseEvent e, JTextField label, Highlighter h) { Highlight[] hls = h.getHighlights(); if (hls == null || hls.length == 0) return false; Highlight hl = hls[0]; FontMetrics fm = label.getFontMetrics(label.getFont()); int offset = getCharOffset(fm, label.getText(), e.getX()); return hl.getStartOffset() <= offset && offset < hl.getEndOffset(); } private static int getCharOffset(FontMetrics fm, String characters, int xPos) { StringBuilder s = new StringBuilder(); char[] sArray = characters.toCharArray(); int i; for (i = 0; i < characters.length() && fm.stringWidth(s.toString()) < xPos; i++) { s.append(sArray[i]); } return i; } }