2

私は単純なJavaSwingベースのアプリケーションに取り組んでいます。フォームの現在フォーカスされているテキストフィールド/テキストエリアのテキストを取得して設定するにはどうすればよいですか?

どのコンポーネントにフォーカスがあるかを判断する方法は知っていますが、コンポーネントの選択したテキストを取得する方法がわかりません。getFocusOwner()を使用しますが、Componentを返すため、getSelectedText()メソッドを実装していません。どういうわけか型キャストを行う必要がありますか?

4

3 に答える 3

3

はい:

Component focusOwner = ...
if(focusOwner instanceof JTextComponent) { // a textfield or textarea is focused
    JTextComponent textComp = (JTextComponent) focusOwner;
    String s = textComp.getText();
}
于 2012-06-26T08:34:00.307 に答える
3

正確なコンテキストに応じて、カスタム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));
于 2012-06-26T10:05:29.767 に答える
2

getFocusOwner()を使用しますが、Componentを返すため、getSelectedText()メソッドを実装していません。どういうわけか型キャストを行う必要がありますか?

方法の1つは、instanceof@user1235867+1をテストすることです。

もう1つの最も効率的な方法は、のアレイをヘルトし、どれに電流が流れているJ/Componentsかを簡単に判断することです。J/ComponentKeyboardFocusManager#getFocusOwner()Window

FocusOwner2つのトップレベルコンテナ間の切り替えはかなり非同期であり、イベントをにラップする必要があることに注意してくださいinvokeLater

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
//http://www.coderanch.com/t/342205/GUI/java/Tab-order-swing-components
public class Testing {

    private static final long serialVersionUID = 1L;
    private Component[] focusList;
    private int focusNumber = 0;
    private JFrame frame;

    public Testing() {
        JTextField tf1 = new JTextField(5);
        JTextField tf2 = new JTextField(5);
        JTextField tf3 = new JTextField(5);
        JButton b1 = new JButton("B1");
        JButton b2 = new JButton("B2");
        tf2.setEnabled(false);
        focusList = new Component[]{tf1, b1, tf2, b2, tf3};
        JPanel panel = new JPanel(new GridLayout(5, 1));
        panel.add(tf1);
        panel.add(b1);
        panel.add(tf2);
        panel.add(b2);
        panel.add(tf3);
        frame = new JFrame();
        frame.setFocusTraversalPolicy(new MyFocusTraversalPolicy());
        frame.add(panel);
        frame.pack();
        frame.setLocation(150, 100);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {

            public boolean dispatchKeyEvent(KeyEvent ke) {
                if (ke.getID() == KeyEvent.KEY_PRESSED) {
                    if (ke.getKeyCode() == KeyEvent.VK_TAB) {
                        Component comp = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
                        if (comp.isEnabled() == false) {
                            if (ke.isShiftDown()) {
                                KeyboardFocusManager.getCurrentKeyboardFocusManager().focusPreviousComponent();
                            } else {
                                KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent();
                            }
                        }
                    }
                }
                return false;
            }
        });
    }

    private class MyFocusTraversalPolicy extends FocusTraversalPolicy {

        public Component getComponentAfter(Container focusCycleRoot, Component aComponent) {
            focusNumber = (focusNumber + 1) % focusList.length;
            return focusList[focusNumber];
        }

        public Component getComponentBefore(Container focusCycleRoot, Component aComponent) {
            focusNumber = (focusList.length + focusNumber - 1) % focusList.length;
            return focusList[focusNumber];
        }

        public Component getDefaultComponent(Container focusCycleRoot) {
            return focusList[0];
        }

        public Component getLastComponent(Container focusCycleRoot) {
            return focusList[focusList.length - 1];
        }

        public Component getFirstComponent(Container focusCycleRoot) {
            return focusList[0];
        }
    }

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

            @Override
            public void run() {
                Testing testing = new Testing();
            }
        });
    }
}
于 2012-06-26T08:55:57.743 に答える