我正在研究一个简单的基于Java swing的应用程序。我将如何获取和设置表单当前关注的文本字段/文本区域的文本?

我知道如何确定哪个组件具有焦点,但是我不知道如何获取组件的选定文本。我使用getFocusOwner(),但它返回一个Component,因此未实现getSelectedText()方法。我是否需要进行类型转换?

最佳答案

根据您的确切上下文,您可能会考虑使用自定义TextAction:其方法getTextComponent(ActionEvent)返回最近关注的文本组件。一个代码片段:

    Action logSelected = new TextAction("log selected") {

        @Override
        public void actionPerformed(ActionEvent e) {
            JTextComponent text = getTextComponent(e);
            System.out.println("selected: " + text.getSelectedText());
        }

    };

    JComponent content = new JPanel();
    content.add(new JTextField("sometext", 20));
    content.add(new JTextField("other content", 20));
    content.add(new JCheckBox("just some focusable comp"));
    content.add(new JButton(logSelected));

09-10 09:26
查看更多