按BACKSPACE时返回上一个控件

时间:2015-09-07 18:15:53

标签: java swing keylistener

我查看了很多网站但没有得到结果。我有一些只接受一个字符的JTextFields。我需要的是,当我按下BACKSPACE时,该字符被清除并且焦点返回到前一个JTextField,依此类推。我向所有JTextFields添加了一个KeyListener,并尝试了KeyTyped,KeyReleased和KeyPressed事件,但都没有。以下代码:

jt.addKeyListener(new KeyAdapter() {

    public void keyTyped(KeyEvent evt) {

        char c = evt.getKeyChar();

        if(Character.isLetter(c) || Character.isISOControl(c))
        {
            evt = evt;  
        } else 
            evt.consume();
    }

    public void keyReleased(KeyEvent evt) {

        if(evt.getKeyChar() == KeyEvent.VK_BACK_SPACE)
        {
            robot.keyPress(KeyEvent.VK_BACK_SPACE);
            robot.keyRelease(KeyEvent.VK_BACK_SPACE);
            robot.keyPress(KeyEvent.VK_SHIFT);
            robot.keyPress(KeyEvent.VK_TAB);
            robot.keyRelease(KeyEvent.VK_TAB);
            robot.keyRelease(KeyEvent.VK_SHIFT);
        }
    }   
});

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

  1. 不要使用KeyListener。 Swing旨在与Key Bindings一起使用。

  2. 不要使用机器人。 API有一个允许您转移焦点的方法。

  3. 以下是密钥绑定的基本代码:

    textField.getInputMap().put(KeyStroke.getKeyStroke("BACK_SPACE"), "backspace");
    textField.getActionMap().put("backspace", new AbstractAction() 
    {
        @Override
        public void actionPerformed(ActionEvent e) 
        {
            Component c = (Component)e.getSource();
                c.transferFocusBackward();
        }
    });
    
      

    我有一些只接受一个字符的JTextField。

    您可能还想查看Text Field Auto Tab。这是一个允许您在输入字符时自动切换到下一个文本字段的类。

答案 1 :(得分:0)

我很快就制作了一个小应用程序,希望能解决您的问题,这里是整个代码:

import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.ArrayList;
import javax.swing.GroupLayout;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

public class BackspaceTest extends JFrame implements KeyListener {

    // In this example I've used 4 Text Fields, each of which takes 1 character
    private JTextField text1, text2, text3, text4;

    // I've stored the Text Fields in a ArrayList so we can easily shuffle trough them later
    private ArrayList<JTextField> fieldList = new ArrayList<>();

    // Numerical value for tracking the currently focused TextField
    private int focusIndex;

    // This constructor is the first thing that gets called from main
    public BackspaceTest() {
        init();
    }

    private void init() {
        // Initialize the text fields with 1 character column size
        text1 = new JTextField(1);
        text2 = new JTextField(1);
        text3 = new JTextField(1);
        text4 = new JTextField(1);

        // Key listeners for implementing 1 character limitations and Backspace functionality
        text1.addKeyListener(this);
        text2.addKeyListener(this);
        text3.addKeyListener(this);
        text4.addKeyListener(this);

        // The focus listener keeps track of currently focused Text Fields
        text1.addFocusListener(new TextFocusListener());
        text2.addFocusListener(new TextFocusListener());
        text3.addFocusListener(new TextFocusListener());
        text4.addFocusListener(new TextFocusListener());

        // The default focus is on the first field
        text1.requestFocus();

        fieldList.add(text1);
        fieldList.add(text2);
        fieldList.add(text3);
        fieldList.add(text4);

        // Puts the items on the screen
        createLayout(text1, text2, text3, text4);

        setTitle("Backspace Test");
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    private void createLayout(JComponent... arg) {
        JPanel panel = (JPanel) getContentPane();
        GroupLayout gl = new GroupLayout(panel);
        panel.setLayout(gl);


        gl.setAutoCreateContainerGaps(true);
        gl.setAutoCreateGaps(true);

        gl.setHorizontalGroup(gl.createSequentialGroup()
            .addComponent(arg[0])
            .addComponent(arg[1])
            .addComponent(arg[2])
            .addComponent(arg[3])
        );

        gl.setVerticalGroup(gl.createParallelGroup()
            .addComponent(arg[0])
            .addComponent(arg[1])
            .addComponent(arg[2])
            .addComponent(arg[3])
        );

        gl.linkSize(text1, text2, text3, text4);

        pack();
    }    

    class TextFocusListener implements FocusListener {

            @Override
            public void focusGained(FocusEvent e) {
                focusIndex = fieldList.indexOf(getFocusOwner());
                System.out.println(focusIndex);
            }

            @Override
            public void focusLost(FocusEvent e) { }

        }

    @Override
    public void keyTyped(KeyEvent e) { }

    @Override
    public void keyPressed(KeyEvent e) { 

        JTextField focusedText = fieldList.get(focusIndex);

//      Check if BACKSPACE is pressed and if Text Field is empty and if it's not the first field
        if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE && 
                focusedText.getText().equals("") &&
                focusIndex > 0) {
            fieldList.get(--focusIndex).requestFocus();
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        // This limits the amount of characteres to 1. I'm not fully pleased with it but it works for this demonstration
        if (text1.getText().length() >= 1)
            text1.setText(text1.getText().substring(0, 1));
        if (text2.getText().length() >= 1)
            text2.setText(text2.getText().substring(0, 1));
        if (text3.getText().length() >= 1)
            text3.setText(text3.getText().substring(0, 1));
        if (text4.getText().length() >= 1)
            text4.setText(text4.getText().substring(0, 1));  
    }

    // Here's where the program starts
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
           @Override
           public void run() {
               new BackspaceTest().setVisible(true);
           }
        });
    }
});

如果您没有时间运行它,请查看第96行,我认为Focus Listener是解决问题的好方法。希望这可以帮助你,祝你好运!