Java JTextField addHighlight(JTextField label, MouseEvent mouseEvent1, MouseEvent mouseEvent2)

Here you can find the source of addHighlight(JTextField label, MouseEvent mouseEvent1, MouseEvent mouseEvent2)

Description

Highlight the given label from the first mouse event to the second Returns true if the highlight was successful, false otherwise.

License

Open Source License

Declaration

public static boolean addHighlight(JTextField label,
        MouseEvent mouseEvent1, MouseEvent mouseEvent2) 

Method Source Code

//package com.java2s;
import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.event.MouseEvent;
import javax.swing.JTextField;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;

public class Main {
    /**//from ww w  .  j a  v a 2  s  .  c om
     * Highlight the given label from the first mouse event to the second
     * Returns true if the highlight was successful, false otherwise.
     */
    public static boolean addHighlight(JTextField label,
            MouseEvent mouseEvent1, MouseEvent mouseEvent2) {
        FontMetrics fm = label.getFontMetrics(label.getFont());
        int firstXpos = mouseEvent1.getX();
        int lastXpos = mouseEvent2.getX();
        int firstOffset = getCharOffset(fm, label.getText(), firstXpos);
        int lastOffset = getCharOffset(fm, label.getText(), lastXpos);
        if (lastOffset != firstOffset) {
            if (firstOffset > lastOffset) {
                int tmp = firstOffset;
                firstOffset = lastOffset;
                lastOffset = tmp;
            }
            try {
                label.getHighlighter().removeAllHighlights();
                label.getHighlighter().addHighlight(
                        firstOffset,
                        lastOffset,
                        new DefaultHighlighter.DefaultHighlightPainter(
                                Color.yellow));
                return true;
            } catch (BadLocationException e1) {
                return false;
            }
        } else
            return false;
    }

    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;
    }
}

Related

  1. addInputValidator(final DocumentListener inputValidator, final JTextField... textFields)
  2. addLabelTextRows(JLabel[] labels, JTextField[] textFields, GridBagLayout gridbag, Container container)
  3. addPlaceHolder(final JTextField field, final String placeHolderText)
  4. addStyle(JTextField textField, String labelName)