日期:2014-05-20  浏览次数:20731 次

请教两个JTextArea相关的问题
在使用JTextArea遇到了两个问题:
1,在一个JFrame中有多个控件组成,其中包含了JTextArea(不是第一个位置) ,窗体打开时 光标 默认的位置在第一个控件上,
怎么设置光标的默认位置呢?也就是说我在打开窗体时,光标要在JTextArea中。
requestFocusInWindow()方法试过了不行。

2,在一个JTextArea中按下 Tab 键,默认的是输出Tab空格在文本域中,怎么实现当按下Tab键时,
光标自动移动到下一个控件上? JTextField 中按下Tab默认是会自动将光标下移的,JTextArea中该怎么实现呢?

在网上找了一个方法:
 JTextArea component = new JTextArea();
   
  // Add actions
  component.getActionMap().put(nextFocusAction.getValue(Action.NAME), nextFocusAction);
  component.getActionMap().put(prevFocusAction.getValue(Action.NAME), prevFocusAction);
   
  // The actions
  public Action nextFocusAction = new AbstractAction("Move Focus Forwards") {
  public void actionPerformed(ActionEvent evt) {
  ((Component)evt.getSource()).transferFocus();
  }
  };
  public Action prevFocusAction = new AbstractAction("Move Focus Backwards") {
  public void actionPerformed(ActionEvent evt) {
  ((Component)evt.getSource()).transferFocusBackward();
  }
  };
但我试过还是不行,请各位兄弟帮帮忙

------解决方案--------------------
Java code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Text {

    public void startup() {
        final JFrame frame = new JFrame("Just a demo");
        final JButton north = new JButton("North");
        final JTextArea text = new JTextArea(15,20);
        final JScrollPane scroller = new JScrollPane(text);
        final JButton south = new JButton("South");
        frame.add(north, BorderLayout.PAGE_START);
        frame.add(scroller, BorderLayout.CENTER);
        frame.add(south, BorderLayout.PAGE_END);
        frame.pack();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
        Action next = new AbstractAction("jumptonext"){
                @Override public void actionPerformed(ActionEvent e){
                    KeyboardFocusManager.getCurrentKeyboardFocusManager().focusNextComponent(text);
                }
            };
        text.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0), "jumpnext");
        text.getActionMap().put("jumpnext",next);
        frame.addWindowListener(new WindowAdapter(){
                @Override public void windowOpened(WindowEvent e){
                    text.requestFocusInWindow();
                }
            });
    }

    public static void main(final java.lang.String[] args) {
        EventQueue.invokeLater(new java.lang.Runnable(){
                @Override public void run(){
                    new Text().startup();
                }
            });
    }
}

------解决方案--------------------
楼上的方法可以借鉴下。
你给JTextArea添加Tab事件
当触发Tab的时候你就在TextArea2中获取焦点。