JTextarea Focus

Hi
Im trying to place the focus in a certain part of a JTextarea after adding text to it. I currently have a JMenuItem which adds text to the JTextarea and I can place the focus with the blinking cursor in the JTextarea, but I cant place the blinking cursor at a certain point of the JTextarea.
I currently have it like so...
txaSQLField.setText("SELECT \n FROM \n WHERE ");
txaSQLField.requestFocus();
I want to place the cursor after the SELECT and before the FROM. I tried
txaSQLField.setText("SELECT ");
txaSQLField.requestFocus();
txaSQLField.setText("\n FROM \n WHERE ");
but it placed the cursor after the WHERE.
Any advice?

textArea.setCaretPosition(....);

Similar Messages

  • JTextArea should get focus...

    Hi everybody,
    I want to accomplish a relatively easy task: when I click on a JButton the text area in my frame should get focus, i.e.: there should be a blinking cursor in the text area and the user should be able to start typing in it right away. However, the text area refuses to get the focus. This is my code:
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTextArea;
    public class TextAreaFocus implements ActionListener
       private static JTextArea text = new JTextArea();
       private static JButton btn = new JButton("Click me");
       public static void main(String[] args)
          // Init the JTextArea.
          text.setText("testje");
          text.setRows(10);
          text.setColumns(50);
          text.setFocusable(true);
          // Create the JPanel for the components.
          JPanel panel = new JPanel(new GridLayout(2, 1));
          panel.add(btn);
          panel.add(text);
          // Create a JFrame to show it all.
          JFrame frame = new JFrame("Testing JTextArea focus");
          frame.add(panel);
          frame.pack();
          frame.setVisible(true);
       public void actionPerformed(ActionEvent e)
          // When the button is clicked the cursor should be placed in the text area.
          // text.requestFocus();
          text.requestFocusInWindow();
    }I guess I am doing / forgetting something really trivial, however I just don't see it.
    Best regards,
    Jethro

    You are right, what i huge mistake! I made this program however, to demonstrate the problem. In my original program (much more complicated that the example off course) requestFocus() does not do the trick. Tomorrow I will try and see if I can give a more complete example which comes closer to the original program.

  • Focus Traversal Problem

    Hello,
    I implemented my own focus traversal policy provider for a JPanel. It appears to be working fine except for one of my components (a JTextArea contained in a JScrollPane). If I ctrl+tab out of the JTextArea, my custom FTP is never used.
    I am still new to the focus subsystem, so I am not sure how to properly debug the situation. I checked the following properties on the JScrollPane and the JTextArea:
    --Focusable:  True for both
    --FocusCycleRootAncestor:  My JPanel for both
    --getFocusTraversalPolicy:  null for both
    --FocusCycleRoot:  False for both
    Since my Custom FTP is not used when tabbing out of the JTextArea, the focus is sent to the wrong component. This is not the only JTextArea in the JPanel (all of them are in JScrollPanes), but it is the only one that with this problem.
    Is there a way for me to detect which FTP is being used? Any ideas why my FTP is not being used?
    Aaron

    Hello,
    I implemented my own focus traversal policy provider for a JPanel. It appears to be working fine except for one of my components (a JTextArea contained in a JScrollPane). If I ctrl+tab out of the JTextArea, my custom FTP is never used.
    I am still new to the focus subsystem, so I am not sure how to properly debug the situation. I checked the following properties on the JScrollPane and the JTextArea:
    --Focusable:  True for both
    --FocusCycleRootAncestor:  My JPanel for both
    --getFocusTraversalPolicy:  null for both
    --FocusCycleRoot:  False for both
    Since my Custom FTP is not used when tabbing out of the JTextArea, the focus is sent to the wrong component. This is not the only JTextArea in the JPanel (all of them are in JScrollPanes), but it is the only one that with this problem.
    Is there a way for me to detect which FTP is being used? Any ideas why my FTP is not being used?
    Aaron

  • JTextArea & Button mnemonic

    Hi!
    I have the following problem (when running in Mac only):
    I have a JTextArea (editable) and a few buttons in a popup. One of the buttons �Send� collects the text written in the text area and does whatever with it. The button�s action can be performed by clicking it and also by using mnemonic.
    In windows my application works just fine.
    When running on the Mac however using the button�s mnemonic while in the JTextArea (focus) a character (alt+d) is being appended to the text before the action is performed.
    I have tried adding the KeyStroke (alt+d) to the JTextArea input map (with �none� as action). It does not work� When adding a dummy action (that only prints to my log file) for this KeyStroke � the printing action is performed but the character is still appended to the text�
    I would really appreciate some advice!
    Thanks!!!
    Here are the relevant code pieces:
    private JTextArea text = new JTextArea(4, 40);
    private JButton send = new JButton(Main.res.getString("sendCanned"));
    // Init Send button.
    send.setEnabled(false);
    send.setMnemonic(KeyEvent.VK_D);
    send.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    handleSend();
    // One of my attempts to add the key stroke to the text input map.
    KeyStroke ks_send = KeyStroke.getKeyStroke(send.getMnemonic(), InputEvent.ALT_MASK);
    text.getInputMap().put(ks_send, "none");

    Mark T. wrote:
    Is it possible to apply some sort of attribute to a button so that it can be fired using an Alt+Key combination, with the appropriate letter underlined on the button text? For example, I want Alt+S to fire the Save button, and I want to underline the S in the word Save on the button label. Possible?Insufficient information (as Re: Setting width of field label):
    <li>Full APEX version?
    <li>Browser(s)/version(s) used?
    <li>Theme?
    <li>Template(s)?
    <li>Button type(s)?
    You might consider the HTML <tt>accesskey</tt> attribute (but see <cite>Building Accessible Websites</cite> for reasons why defining <em>any</em> keyboard shortcuts outside of those built-in to the browser may be problematic.)
    As to indicating the shortcut key in the button label, that depends on the information you've left out...

  • JTextArea over JLabel(image for background) Can't Receive Mouse Events

    Hi, I use JLabel for putting background image to a JWindow. But when i put a JTextArea component, i can see and edit the contents but JtextArea only receives keyboard events. When i click on it ,its Focus Gained Event is not fired. No blinking cursor is shown.
    I tried to use JLayeredPane and put them on different layers but it doesn't solve the problem.
    I searched the Forums but can't find a suitable answer.
    Any comments please...

    hey man,
    your problem happen not because your JTextArea over a JLabel, but cause JWindow not take focuse before jdk1.4, so if you need to see your blinking cursor just replace your JWindow with a JFrame.
    for the JTExtArea focusing problem, u may refer to the sun bug forum there is a lot of work around.

  • JTextField and JTextArea don't get focus occuasionally

    I am developing a Java Swing Applet. At edit mode, JComboBox, JCheckBox, JRadioBox, and JButton work fine, but JTextField and JTextArea can't get focus occuasionally while I click them.
    Anyone has idea?
    Thanks

    Thank you Himanshu,
    but that's not exactly what my issue is. This link describes the undesired effect of ending up outisde of the player window and in the browser.
    My problem is kind of the opposite. When I launch the page in the html file I cannot use the tab key to get to any of the controls in the captivate window. I'm stuck in the browser unless I click on the captivate window. That is not acceptable if we want it accessible without using a mouse. I found a way to make it work for chrome like I stated above, but not in FF. Do you have any ideas for this?
    Thanks!
    Monique

  • Focusable JTextArea not gaining focus.

    I am creating a JTextArea and want to give it the focus when it's created. THis happens twice in the program, and the first time it works, the second time the JTextArea is created but doesn't get the focus until I click on it.
    In both cases the code is called from the Swing event queue (see the output below). In both cases the class which creates the jTextArea is the same (an extension of JPanel), and is added to a new tab in a tabbed pane.
    Because I know that you need to make sure that the component's been created before it gets focus, the code to create it and give it focus is:
    private javax.swing.JTextArea jtaInfo;
    // Class constructor for outer class
      public PanelInfo(String s, boolean editable ) {
        initComponents();  // this is the NetBeans call which creates jtaInfo and a few buttons
        jtaInfo.setText(s);
        jtaInfo.setEditable(editable);
        setVisible(true);
        selectTextBox();
      public void selectTextBox() {
        UtilFunctions.tcaProgramInfoMessage("selectTextBox thread="+Thread.currentThread().getName());
        SwingUtilities.invokeLater(new Runnable() {
          public void run() {
            UtilFunctions.tcaProgramInfoMessage("Runnable thread="+Thread.currentThread().getName());
            UtilFunctions.tcaProgramInfoMessage("Info frame focusable: "+jtaInfo.isFocusable());
            if (!jtaInfo.requestFocusInWindow()) {
              UtilFunctions.tcaProgramInfoMessage("Failed to give info pane focus");
      }The UtilFunctions.tcaProgramInfoMessage call produces output with a timestamp.
    The output is:
    Sat Nov 11 11:25:38 GMT 2006: selectTextBox thread=AWT-EventQueue-0
    Sat Nov 11 11:25:38 GMT 2006: Runnable thread=AWT-EventQueue-0
    Sat Nov 11 11:25:38 GMT 2006: Info frame focusable: true
    Sat Nov 11 11:25:44 GMT 2006: selectTextBox thread=AWT-EventQueue-0
    Sat Nov 11 11:25:44 GMT 2006: Runnable thread=AWT-EventQueue-0
    Sat Nov 11 11:25:44 GMT 2006: Info frame focusable: true
    Sat Nov 11 11:25:44 GMT 2006: Failed to give info pane focus
    So it seems that the threads are OK, and the area is focusable, but I can't work out why one succeeds and the other fails. The program's too huge to post here - I may be able to cut it down to size. But is there anything obvious that I might be doing wrong?

    Because I know that you need to make sure that the component's been created before it gets focus,Actually the parent frame or dialog must be "realized" (maybe thats what you mean by "created") before a component can receive focus. This basically means that you've done a pack() or setVisible(true) on the frame. Using setVisible(true) on the actual component does nothing since by default all JComponents are visible.
    The program's too huge to post here - I may be able to cut it down to sizeI fail to see why its so difficult to create a short demo program showing the problem. The code you posted doesn't help because we don't know the context of how the code is executed.
    Below is a simple demo that shows an incorrect version and a correct version in 10 lines of code. So if this code doesn't help solve the problem you will now need to wait hours again until you post a version of your code that does demonstrate the problem. Whereas if you had spent 5-10 minutes to create a demo that doesn't work I may have been able to help you out right now.
    Simplify your problems and the answer will also be simpler.
    import java.awt.*;
    import javax.swing.*;
    public class FocusTest
         public static void main(String[] args)
              JTextField textField1 = new JTextField("One");
              JTextField textField2 = new JTextField("Two");
              JTextField textField3 = new JTextField("Three");
              JFrame frame = new JFrame();
              frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
              frame.getContentPane().add(textField1, BorderLayout.NORTH);
              frame.getContentPane().add(textField2, BorderLayout.CENTER);
              frame.getContentPane().add(textField3, BorderLayout.SOUTH);
              // This doesn't work
              textField3.requestFocusInWindow();
              frame.pack();
              // This does work
    //          textField3.requestFocusInWindow();
              frame.setLocationRelativeTo(null);
              frame.setVisible(true);
    }

  • JTextArea not gaining focus

    I have a tabbed pane consisting of 2 JPanels. Each panel has a text area (within a scrollpane) on both.
    All I want is for the text area to gain focus when its tab has been clicked.
    I've tried adding a changelistener to the tabbedpane:
            tabbedPane.addChangeListener(new ChangeListener() {
                public void stateChanged(ChangeEvent e) {
                    if (tabbedPane.getSelectedIndex() == 0) {
                        textArea1.requestFocus();
                    else {
                        textArea2.requestFocus();
            });but the textareas don't get focus. They do when I press <TAB> but this isn't much use.
    Does anyone have any ideas how I can get the textareas to gain focus?

    import javax.swing.*;
    import javax.swing.event.ChangeListener;
    import javax.swing.event.ChangeEvent;
    import java.awt.*;
    public class TestFocusTabbedPane extends JTabbedPane {
         private JTextArea theFirstTextArea;
         private JTextArea theSecondTextArea;
         public TestFocusTabbedPane() {
              super();
              JPanel tabPanel = new JPanel(new BorderLayout());
              tabPanel.add(new JButton("just for test"), BorderLayout.NORTH);
              theFirstTextArea = new JTextArea();
              theFirstTextArea.setFocusable(true);
              tabPanel.add(new JScrollPane(theFirstTextArea), BorderLayout.CENTER);
              addTab("first", tabPanel);
              tabPanel = new JPanel(new BorderLayout());
              tabPanel.add(new JButton("just for test"), BorderLayout.NORTH);
              theSecondTextArea = new JTextArea();
              theSecondTextArea.setFocusable(true);
              tabPanel.add(new JScrollPane(theSecondTextArea), BorderLayout.CENTER);
              addTab("second", tabPanel);
              addChangeListener(new ChangeListener() {
                   public void stateChanged(ChangeEvent e) {
                        int index = getSelectedIndex();
                        if (index == 0) {
                             theFirstTextArea.requestFocus();
                        } else {
                             theSecondTextArea.requestFocus();
         public static void main(String[] args) {
              final JFrame frame = new JFrame(TestPressedButton.class.getName());
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.getContentPane().add(new TestFocusTabbedPane());
              SwingUtilities.invokeLater(new Runnable() {
                   public void run() {
                        frame.pack();
                        frame.show();
    }This seems to work. I added the JButton just to show that it doesn't get the focus

  • Focus in JTextArea (JDK1.4)

    hi,
    I try to tab in a JTextArea when I use JDK 1.4. But new focus traversal policy in JDK 1.4 does not include JTextArea. Anybody has any idea how to do this: the focus should be on the selected line or the first line by default whenever pressing Tab key into a JTextArea? Thanks anyway.

    hi,
    maybe when you reactivate the browser, you reactivate the site(!) and not the applet.
    The applet is only a part of the site and has to be activated, too.
    I guess this is the problem.
    but i got no idea how to fix this.
    sorry.
    cu Errraddicator

  • Moving the Focus with the TAB key in a JTextArea Component

    Dear Friends,
    I have exhausted all options of moving focus from JTextArea to next component. I have also tried all suggestions available in this forum. But i'm not able to solve my problem. Can any one help me.
    Thanx in advance.

    I had the same problem before. Here is what i did.
    JTextArea txtArea = new JTextArea(2,15);
    Set forwardTraversalKeys = new HashSet();     
    forwardTraversalKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0));          
    txtArea.setFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,forwardTraversalKeys);          
    Set backwardTraversalKeys = new HashSet();          
    backwardTraversalKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, InputEvent.SHIFT_MASK));          
    txtArea.setFocusTraversalKeys( KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS, backwardTraversalKeys);
    JScrollPane scrollPane = new JScrollPane(
         txtArea,
            JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
            JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    // the scrollbar of the JScrollPane is focusable that's why it requires
    // another TAB key to transfer the focus.
    scrollPane.getVerticalScrollBar().setFocusable(false);

  • Using TAB to focus next component in a JTextArea

    hello everybody,
    I would like to use the TAB-key in a JTextArea to focus the next component in my frame.
    I tried to use an KeyListener which calls an instance of javax.swing.FocusManager with the method
    focusNextComponent(Component c).
    My problem is, that - allthough I call consume() for the KeyEvent - the TAB is displayed im my JTextArea........
    how can I solve this, that the TAB is NOT visible?
    (plaese excuse my bad english )
    Thanks Chris

    The way to do it is use setNextFocusableComponent(Component c)
    so as you create each component, you can set the order that the tab key will give focus.
    eg
    JButton b1 = new JButton();
    JButton b2 = new JButton();
    b1.setNextFocusableComponent(b2);
    etc...
    The tab won't be displayed in the JTextArea then,.
    James

  • Tab not changing focus in a JTextArea

    Hi
    I am writing a little program that at a certain point uses a JTextArea. What bugs me a lot is that the JTextArea keeps focus when I press the Tab button
    I see two solutions to this.
    Either I extend JTextArea into MyJTextArea and override the processKeyEvent method and from there address the processKeyEvent method from JTextComponent class
    so the processKeyEvent method from JTextArea never gets a chance at catching the tab.
    The second solution would be to once again extend the JTextArea class and override the processKeyEvent method, and in the method check whether tab was pressed, and in that case change the focus myself
    I don't know if the first is possible, but the second should work. I'm actually rather curious about the first one. So if anyone can help me out in either addressing the super-superclass of MyJTextArea or in changing the focus manually without creating too much of a fuss, I'd be very, very thankfull
    Thx in advance!
    Pieter

    the previous post it's rigth, you can leave the JTextArea using ctrl+tab, but if you really need pass the focus out of the JTextArea with only press tab you can do something like this     myTextArea.setDocument(new PlainDocument() {
              public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
                  if (str.equalsIgnoreCase("\t"))
                        FocusManager.getCurrentManager().focusNextComponent(myTextArea);
                   else
                        super.insertString(offs, str, a);
         }); hope this helps
    lalo s.

  • Customize "Tab" key for JTextArea to focus next component.

    Hi,
    I am trying to change the "TAB" key behaviour for JTextArea, by using CustomAction configured via InputMap() and ActionMap(). When the user presses the Tab key, the focus should go the next component instead of tabbing in the same JTextArea component. Here is the code for the CustomAction().
        public static class CustomTabAction extends AbstractAction {
            private JComponent comp;
            public CustomTabAction (JComponent comp) {
                this.comp = comp;
                this.comp.getInputMap().put(KeyStroke.getKeyStroke("TAB"), "TABPressed");
                this.comp.getActionMap().put("TABPressed", this);
            public void actionPerformed(ActionEvent evt) {
                Object source = evt.getSource();
                if (source instanceof Component) {
                    FocusManager.getCurrentKeyboardFocusManager().
                            focusNextComponent((Component) source);
        }This works for most of the cases in my applicaiton. The problem is that it doesn't work with JTable which has a custom cell editor (JTextArea). In JTextArea field of JTable, if the Tab is pressed, nothing happens and the cursor remains in the custom JTextArea exactly at the same place, without even tabbing spaces. Here is the CustomCellEditor code.
        public class DescColCellEditor extends AbstractCellEditor implements TableCellEditor {
    //prepare the component.
            JComponent comp = new JTextArea();
            public Component getTableCellEditorComponent(JTable table, Object value,
                    boolean isSelected, int rowIndex, int vColIndex) {
                // Configure Tab key to focus to next component
                CustomActions.setCustomAction("CustomTabAction", comp);
                // Configure the component with the specified value
                ((JTextArea)comp).setText((String)value);
                // Return the configured component
                return comp;
            // This method is called when editing is completed.
            // It must return the new value to be stored in the cell.
            public Object getCellEditorValue() {
                return ((JTextArea)comp).getText();
        }regards,
    nirvan

    >
    textArea.getInputMap().remove(....);but that won't work because the binding is actually defined in the parent InputMap. So I think you need to use code like:
    textArea.getInputMap().getParent().remove(...);But I'm not sure about this as I've never tried it.I tried removing the VK_TAB key from both the input map and parent input map as shown below. But I still have to press "TAB" twice in order to get out of the JTextArea column in JTable.
                comp.getInputMap().getParent().remove(
                            KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0));
                comp.getInputMap().remove(
                            KeyStroke.getKeyStroke(KeyEvent.VK_TAB,0));after coding this, I am using the setFocusTraversalKeys for adding only "TAB" key as ForwardTraversalKey as given below.
            Set newForwardKeys = new HashSet();
            newForwardKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0));
            comp.setFocusTraversalKeys(
                        KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS,newForwardKeys);
            Set newBackwardKeys = new HashSet();
            newBackwardKeys.add(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, KeyEvent.SHIFT_DOWN_MASK));
            comp.setFocusTraversalKeys(
                        KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS,newBackwardKeys);The only problem that remains now is that I have to press the "TAB" twice in order to get out of the JTextArea column
    regards,
    nirvan.

  • Setting focus to a JTextArea using tab

    Hi,
    I have a JPanel with a lot of controls on it. When I press tab I want to
    move focus to the next focusable component. This works fine for
    JTextFields, but when the next component is a JTextArea in a
    JScrollPane then I have to press tab 3 times to set the focus to the
    JTextArea. After pressing the tab key once I think the focus is set to
    the scrollBars of the JTextArea because when I press the up and down
    arrows the textarea is scrolled.
    How can I stop the JScrollPane from getting the focus?
    I have tried to set focusable to false on the scrollPane:
    scrollPanel.setFocusable(false);
    and the scrollBars of the scrollPane:
    scrollPanel.getHorizontalScrollBar().setFocusable(false);
    scrollPanel.getVerticalScrollBar().setFocusable(false);
    But it dosen�t work. Is this a completely wrong way of doing it?
    Please help!
    I use jdk 1.4.1
    :-)Lisa

    Not sure what your problem is. The default behaviour is for focus to go directly to the JTextArea.
    import java.awt.*;
    import javax.swing.*;
    public class Test1 extends JFrame
         public Test1()
              getContentPane().add( new JTextField("focus is here"), BorderLayout.NORTH );
              getContentPane().add( new JButton("Button1") );
              getContentPane().add( new JScrollPane( new JTextArea(5, 30) ), BorderLayout.SOUTH );
         public static void main(String[] args)
              Test1 frame = new Test1();
              frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
              frame.pack();
              frame.setVisible(true);
    }

  • How to use tab key with JTextArea to shift focus

    Hi
    My problem is simple as whenevr i use tab key in my JTextArea, instaed of shifting focus to next component, it adds a tab space to my text.
    How do i shift focus out of my JTextArea.
    Ashish

    you can also redefine the textarea's TAB Key behaviour. The tutorial has a good example for that - better than i would be able to describe :-)
    look at http://java.sun.com/docs/books/tutorial/uiswing/misc/keybinding.html

Maybe you are looking for