首页 > 解决方案 > 如何在 JLabel 或 JEditorPane 中指定选择

问题描述

我需要在我的应用程序中通过单击单词或选择一段文本来为所选单词添加下划线。

所以我的第一个想法是使用 a JLabel,因为它解析文本 asHTML但我不知道如何知道点击的单词然后我尝试JEditorPane了它,但它没有像我使用 aMouseListener mouseReleased()来为所选文本加下划线那样预期。

  public void mouseReleased (MouseEvent e){
if (jEditorPane.getSelectedText()==null ||jEditorPane.getSelectedText().equals(""))
        return;
//to know the get real location of the text
//because by default the editorpane will add the rest of the html elements
// to the text to make look like a proper page
    int x1=jEditorPane.getText().indexOf("<body>")+"<body>".length();
    int x2=jEditorPane.getText().indexOf("</body>");
//the editor pane will add few white spaces after the body tag
    String trim = (jEditorPane.getText().subSequence(x1, x2)+"").trim();
    int selectionStart = jEditorPane.getSelectionStart();
    int selectionEnd = jEditorPane.getSelectionEnd();
    String text = trim;
    String beg = text.substring(0,selectionStart);
    String mid = "<U>"+text.substring(selectionStart,selectionEnd)+"</U>";
    String end = text.substring(selectionEnd,text.length());
    jEditorPane.setText(beg+mid+end);

}

问题是所选文字不准确!我的一些选择带有下划线,有些没有,我需要使其准确或在点击的单词下划线并提前感谢。(JEditorPane如果您有更好的想法,则不需要)

标签: javaswing

解决方案


基于使用 JTextPane 制作文本下划线字体?以及如何获取 JTextArea 中的单词(或选择)在屏幕上的位置的点值?我能够生产...

用鼠标标记文本

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;
import javax.swing.text.StyledDocument;
import javax.swing.text.Utilities;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JEditorPane editorPane;

        public TestPane() {
            editorPane = new JEditorPane();
            editorPane.setContentType("text/html");
            editorPane.setText("<html>Hello world, this is a test</html>");
            setLayout(new BorderLayout());
            add(new JScrollPane(editorPane));

            editorPane.addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    Point point = e.getPoint();
                    Range range = getRangeOfWordUnderMouse(editorPane, point);
                    //String word = getWordUnderMouse(editorPane, point);
                    SimpleAttributeSet as = new SimpleAttributeSet();
                    StyleConstants.setUnderline(as, true);
                    ((StyledDocument)editorPane.getDocument()).setCharacterAttributes(range.getFrom(), range.length(), as, false);
                }

            });
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

    }

    public static class Range {
        private int from;
        private int to;

        public Range(int from, int to) {
            this.from = from;
            this.to = to;
        }

        public int getFrom() {
            return from;
        }

        public int getTo() {
            return to;
        }

        public int length() {
            return to - from;
        }

    }

    public static Range getRangeOfWordUnderMouse(JTextComponent textComp, Point2D point) {
        int pos = textComp.viewToModel2D(point);
        try {
            Document doc = textComp.getDocument();
            if (pos > 0 && (pos >= doc.getLength() || Character.isWhitespace(doc.getText(pos, 1).charAt(0)))) {
                // if the next character is a white space then use 
                // the word on the left side..
                pos--;
            }
            // get the word from current position
            final int begOffs = Utilities.getWordStart(textComp, pos);
            final int endOffs = Utilities.getWordEnd(textComp, pos);

            return new Range(begOffs, endOffs);
        } catch (BadLocationException ex) {
            // Ignore this exception!!!
            ex.printStackTrace();
        }
        return null;
    }

    public static String getWordUnderMouse(JTextComponent textComp, Point2D point) {
        Range range = getRangeOfWordUnderMouse(textComp, point);
        if (range == null) {
            return "";
        }

        try {
            return textComp.getText(range.getFrom(), range.length());
        } catch (BadLocationException ex) {
            ex.printStackTrace();;
        }
        return "";
    }

}

您可以使用许多其他概念,例如确定选择的范围,我没有显示,但在链接中提到


推荐阅读