javafx Position der Bustaben finden label

Du willst die Positionen der Buchstaben in einem Label finden? Das ist nicht so einfach, aber über FontMetrics sollte das möglich sein.

Beispiel:

Java:
import javax.accessibility.AccessibleText;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MyLabel {
    private final JLabel textLabel = new JLabel("<html>First line<br>Second line</html>");

    public MyLabel() {
        JFrame frame = new JFrame();

        frame.add(textLabel);
        frame.setSize(200, 200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        frame.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                printPositions();
            }
        });
    }

    public void printPositions() {
        Point location = textLabel.getLocation();
        FontMetrics fontMetrics = textLabel.getGraphics().getFontMetrics();
        AccessibleText text = textLabel.getAccessibleContext().getAccessibleText();
        int x = location.x;
        int y = location.y;
        int height = fontMetrics.getHeight() / (int) text.getAfterIndex(AccessibleText.CHARACTER, 0).lines().count();
        for (int i = 0; i < text.getCharCount(); i++) {
            char ch = text.getAtIndex(AccessibleText.CHARACTER, i).charAt(0);
            Rectangle rectangle = new Rectangle(x, y, fontMetrics.getWidths()[i], height);
            x += fontMetrics.getWidths()[i];
            if (ch == 10) {
                x = location.x;
                y += height;
            }
            System.out.println(ch + " " + (int) ch + " == (" + rectangle.getCenterX() + "," + rectangle.getCenterY() + ")");
        }
    }

    public static void main(String[] args) {
        MyLabel myLabel = new MyLabel();
        myLabel.printPositions();
    }
}

Nur anstatt Swing Fx verwenden...
 

Zurück
Oben