Is there something already built into Swing that allows you to get the handle to the last text component that had focus?
You create an action that extends TextAction. The TextAction class has a method that allows you to get the last text component with focus.
Edit:
You can create your own action and do whatever you want. You can then add the action to any JMenuItem or JButton. For instance:
class SelectAll extends TextAction { public SelectAll() { super("Select All"); } public void actionPerformed(ActionEvent e) { JTextComponent component = getFocusedComponent(); component.selectAll(); } }
If you just want to insert a character in the caret position of the text field, you can simply do
component.replaceSelection(...);
Edit 2:
I do not understand what confusion is with this answer. Here is a simple example:
- select text
- use mouse to click this check box.
- or use the mouse to click the "Cut" button
It doesn't matter that the text field currently has no focus when calling Action. TextAction tracks the last text component with focus.
import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.text.*; public class TextActionTest extends JFrame { JTextField textField = new JTextField("Select Me"); JTabbedPane tabbedPane; public TextActionTest() { add(textField, BorderLayout.NORTH); add(new JCheckBox("Click Me!")); add(new JButton(new CutAction()), BorderLayout.SOUTH); } public static void main(String[] args) { TextActionTest frame = new TextActionTest(); frame.setDefaultCloseOperation( EXIT_ON_CLOSE ); frame.pack(); frame.setLocationRelativeTo( null ); frame.setVisible(true); } class CutAction extends TextAction { public CutAction() { super("Click to Cut Text"); } public void actionPerformed(ActionEvent e) { JTextComponent component = getFocusedComponent();
source share