To make a copy/paste action as general as possible in an application - what would be the most effective way to get hold of the current selection without knowing which component owns the focus/the selected area?

Sandip Chitale

Yes. That is how all the Actions work in the JTextComponent. The methods are in javax.swing.text.TextAction. Here is the code snippet -

     * Determines the component to use for the action.
     * This if fetched from the source of the ActionEvent
     * if it's not null and can be narrowed.  Otherwise,
     * the last focused component is used.
     * @param e the ActionEvent
     * @return the component
    protected final JTextComponent getTextComponent(ActionEvent e) {
	if (e != null) {
	    Object o = e.getSource();
	    if (o instanceof JTextComponent) {
		return (JTextComponent) o;
	return getFocusedComponent();

     * Fetches the text component that currently has focus.
     * This allows actions to be shared across text components
     * which is useful for key-bindings where a large set of
     * actions are defined, but generally used the same way
     * across many different components.
     * @return the component
    protected final JTextComponent getFocusedComponent() {
	return JTextComponent.getFocusedComponent();

0 Comments  (click to add your comment)
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact
We have made updates to our Privacy Policy to reflect the implementation of the General Data Protection Regulation.