2

I am working on a simple java swing based application. How would I get and set the text of the currently focused textfield/textarea of a form?

I know how to determine which component has focus but I can not figure out how I can get the selected text of the component. I use getFocusOwner() but it return a Component and therefore does not implement the method getSelectedText(). Do I somehow need to do a typecast?

Nordanfors
  • 371
  • 1
  • 4
  • 9
  • Welcome to SO. Show us [what you have tried](http://mattgemmell.com/2008/12/08/what-have-you-tried/)..., preferably as a [SSCCE](http://sscce.org/). To get help with your code, you need to show us your code... – amaidment Jun 26 '12 at 08:26

3 Answers3

3

Yes:

Component focusOwner = ...
if(focusOwner instanceof JTextComponent) { // a textfield or textarea is focused
    JTextComponent textComp = (JTextComponent) focusOwner;
    String s = textComp.getText();
}
lbalazscs
  • 17,474
  • 7
  • 42
  • 50
  • 1
    the type-cast is just fine - but depending on context, might not grab the text component as expected, f.i. if queried inside a button's action - at that time the button may be the focus owner. – kleopatra Jun 26 '12 at 10:09
3

Depending on your exact context, you might consider to use a custom TextAction: its method getTextComponent(ActionEvent) returns the most recent focused text component. A code snippet:

    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));
kleopatra
  • 51,061
  • 28
  • 99
  • 211
  • Thank you! This is a good approach. A bit more robust than the previous example so I think I'll go with this. – Nordanfors Jun 26 '12 at 14:27
2

I use getFocusOwner() but it return a Component and therefore does not implement the method getSelectedText(). Do I somehow need to do a typecast?

one of ways is testing for instanceof @user1235867 +1

another and most efficient is to helt arrays of J/Components and the to simple to determine which of J/Component has current KeyboardFocusManager#getFocusOwner() in the Window

notice switching with FocusOwner betweens two Top-Level Containers is pretty asynchronous and required wrapping events into 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();
            }
        });
    }
}
mKorbel
  • 109,525
  • 20
  • 134
  • 319