How to get selection from JTextPane

删除回忆录丶 提交于 2019-12-06 04:18:47

Have a look at JTextComponent#getSelectedText(). You'd simply call this method on the instance of your JTextPaneand it will return the selected text of your JTextPane. Did a small example:

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class JavaApplication101 {

    private JTextPane jTextPane;
    private JButton btnGetSelectedText;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new JavaApplication101().createAndShowUI();
            }
        });
    }

    private void createAndShowUI() {

        JFrame frame = new JFrame("Test");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        initComponents(frame.getContentPane());
        frame.pack();
        frame.setVisible(true);
    }

    private void initComponents(Container contentPane) {
        jTextPane = new JTextPane();
        btnGetSelectedText = new JButton("Get selected text");

        btnGetSelectedText.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null, jTextPane.getSelectedText());
            }
        });
        contentPane.add(jTextPane, BorderLayout.NORTH);
        contentPane.add(btnGetSelectedText, BorderLayout.SOUTH);
    }
}
public class TextPaneHighlightsDemo extends JFrame {

public TextPaneHighlightsDemo() {
    super("SplashScreen demo");
    setSize(300, 200);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    final JTextPane textPane = new  JTextPane();
    add(textPane);
    textPane.addCaretListener(new CaretListener() {

        @Override
        public void caretUpdate(CaretEvent e) {
            Highlight[] h = textPane.getHighlighter().getHighlights();
            for(int i = 0; i < h.length; i++) {
                System.out.println(h[i].getStartOffset());
                System.out.println(h[i].getEndOffset());
            }

        }
    });
        }

public static void main (String args[]) {
    TextPaneHighlightsDemo test = new TextPaneHighlightsDemo();
    test.setVisible(true);
}
}

I found my problem - that was a custom FocusListener which was changing JTextPane content (and so dropping the selection) before I got the keyTyped event.

Anyway, thanks everyone for examples and comments!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!