简体   繁体   中英

How to check that text was selected in Swing?

I have simple JTextField and KeyListener.

JTextField textField = new JTextField();
textField.addKeyListener(new KeyListener() {

@Override
   public void keyTyped(KeyEvent e)
   {
   }

   @Override
   public void keyPressed(KeyEvent e)
   {
   }

   @Override
   public void keyReleased(KeyEvent e)
   {
      validateThatTextWasSelectedWithShiftAndArrow();
   }
});

How do I check that someone select text with key combination (SHIFT + LEFT or RIGHT ARROW) ?

Swing makes heavy use of the Key Bindings API to make it easy to work with existing functionality. We already know the JTextField is fully capable of performing selection, we just need to be able to plug into it.

The JTextField uses the selection-backward and selection-forward to execute the required functionality when the system dependent key strokes are activated, we just need to inject our code into it.

For this, I wrote a simple ReplaceAction action, which takes the old Action we are interested, and calls two methods, one before and one after the old Action is called. This allows you to inject your required functionality into whatever point is required to achieve whatever functionality you are trying to implement...

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class MonitorSelection {

    public static void main(String[] args) {
        new MonitorSelection();
    }

    public MonitorSelection() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        public TestPane() {
            setLayout(new GridBagLayout());
            JTextField field = new JTextField(10);
            add(field);
            InputMap im = field.getInputMap(WHEN_FOCUSED);
            ActionMap am = field.getActionMap();

            Action oldAction = am.get("selection-backward");
            am.put("selection-backward", new ReplacedAction(oldAction){
                @Override
                protected void doAfterReplacedAction() {
                    System.out.println("Before selection-backward");
                }

                @Override
                protected void doBeforeReplacedAction() {
                    System.out.println("After selection-backward");
                }

            });
            oldAction = am.get("selection-forward");
            am.put("selection-forward", new ReplacedAction(oldAction){
                @Override
                protected void doAfterReplacedAction() {
                    System.out.println("Before selection-forward");
                }

                @Override
                protected void doBeforeReplacedAction() {
                    System.out.println("After selection-forward");
                }

            });
        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(200, 200);
        }

    }

    public class ReplacedAction extends AbstractAction {
        private Action replaced;

        public ReplacedAction(Action replaced) {
            this.replaced = replaced;
        }

        @Override
        public void actionPerformed(ActionEvent e) {
            doBeforeReplacedAction();
            replaced.actionPerformed(e);
            doAfterReplacedAction();
        }

        protected void doBeforeReplacedAction() {
        }

        protected void doAfterReplacedAction() {
        }

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM