【问题标题】:How to get selection from JTextPane如何从 JTextPane 中获取选择
【发布时间】:2015-07-15 19:39:46
【问题描述】:

我想知道选择了 JTextPanel 文本的哪一部分。尝试调用JTextPane.getSelectionStart()JTextPane.getSelectionEnd(),但它们总是返回与当前插入符号位置相同的值。 我的问题是什么?

我会感谢任何获得当前选择的代码示例。

【问题讨论】:

标签: java swing selection jtextpane


【解决方案1】:

看看JTextComponent#getSelectedText()。您只需在 JTextPane 的实例上调用此方法,它将返回您的 JTextPane 的选定文本。做了一个小例子:

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

【讨论】:

    【解决方案2】:
    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);
    }
    }
    

    【讨论】:

      【解决方案3】:

      我发现了我的问题 - 那是一个自定义 FocusListener 在我收到 keyTyped 事件之前正在更改 JTextPane 内容(因此放弃选择)。

      无论如何,谢谢大家的例子和cmets!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-07-19
        • 1970-01-01
        • 2015-09-03
        • 1970-01-01
        • 1970-01-01
        • 2014-06-13
        • 1970-01-01
        相关资源
        最近更新 更多