How can I modify the behavior of the tab key in a JTextArea?

前端 未结 4 1930
猫巷女王i
猫巷女王i 2020-12-09 17:57

I\'m creating a form in Java Swing, and one of the fields is a JTextArea. When I use the Tab key on all other fields, it gives the focus to the next

4条回答
  •  一向
    一向 (楼主)
    2020-12-09 18:32

    You can call the following method in your main JFrame or JPanel constructor. Use by calling as so: disableTabbingInTextAreas(this)

    public static void disableTabbingInTextAreas(Component component){
        if(component instanceof Container && !(component instanceof JTextArea)){
            for(final Component c : ((Container) component).getComponents() ){
                disableTabbingInTextAreas(c);
            }
        }else if(component instanceof JTextArea){
            final Component c = component;
            c.addKeyListener(new KeyListener() {
                @Override
                public void keyTyped(KeyEvent e) {}
    
                @Override
                public void keyPressed(KeyEvent e) {
                    if(e.getKeyChar() == '\t'){
                        c.transferFocus();
                        e.consume();
                    }
                }
    
                @Override
                public void keyReleased(KeyEvent e) {}
            });
        }
    }
    

提交回复
热议问题