TextHitInfoDemo.java Source code

Java tutorial

Introduction

Here is the source code for TextHitInfoDemo.java

Source

import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.font.FontRenderContext;
import java.awt.font.TextHitInfo;
import java.awt.font.TextLayout;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class TextHitInfoDemo extends JPanel {
    private TextLayout mTextLayout;

    private int mX = 40, mY = 80;

    public TextHitInfoDemo() {
        addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent me) {
                TextHitInfo hit = mTextLayout.hitTestChar(me.getX() - mX, me.getY() - mY);
                System.out.println(hit);
            }
        });
    }

    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;

        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        String s = "Java Source and Support";
        Font font = new Font("Serif", Font.PLAIN, 32);

        if (mTextLayout == null) {
            FontRenderContext frc = g2.getFontRenderContext();
            mTextLayout = new TextLayout(s, font, frc);
        }

        mTextLayout.draw(g2, mX, mY);
    }

    public static void main(String[] args) {
        JFrame f = new JFrame();
        f.getContentPane().add(new TextHitInfoDemo());
        f.setSize(200, 200);
        f.show();
    }

}