Which event a selection of text trigger in Java JTextArea?

故事扮演 提交于 2019-12-24 02:26:05

问题


I want to monitor the selection of text into the a JTextArea. I don't know what event a selection of text triggers.

I just want to enable some of the menu items as soon as some text is selected out of the JTextArea like copy and cut options into the menu. What should I monitor for that?


回答1:


I don't know about any "selection listeners" for text components (although they might be useful), but you could use a CaretListener to monitor changes to the caret position and check the selection state...

public class TestSelectionMonitor {

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

    public TestSelectionMonitor() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                final JTextArea ta = new JTextArea();
                ta.addCaretListener(new CaretListener() {
                    @Override
                    public void caretUpdate(CaretEvent e) {
                        int length = ta.getSelectionEnd() - ta.getSelectionStart();
                        System.out.println(length);
                    }
                });

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new JScrollPane(ta));
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}


来源:https://stackoverflow.com/questions/15147016/which-event-a-selection-of-text-trigger-in-java-jtextarea

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