We help IT Professionals succeed at work.

JTextField focus

epastoor
epastoor asked
on
I have a frame with about 20 Jtextfields. I currently have the tab order to go from one textfield to the next. This is what i want. However, i want it so that when you tab from JTextField to JTextField, the focus of the cursor to select the text so that when you type text in the jtextfield you dont have to delete the text that is already there.
Comment
Watch Question

Ovi

Commented:
So you want that the text to be selected or to be not ? I don't clear understand what you want.
Anyway, you have to implement in your container class (the one which holds the textfield) a FocusListener and to add this listener to every textfield. When you receive the event FOCUS_GAIGNED use the JTextComponent method on the focused component selectAll() for selecting thwe whole text, or textField.select(0, 0) to clear the selection.

Author

Commented:
i want the entire text of that jtextfield to be selected.  HOw do i create this focuslistener?

Author

Commented:
i want the entire text of that jtextfield to be selected.  HOw do i create this focuslistener?

Commented:
This will add a focus listener to the text field. When the text field gets the focus, its text will be highlighted.

JTextField textField = new JTextField(8);
textField.addFocusListener(
   new FocusListener() {
      public void focusGained(FocusEvent focusEvent) {
         JButton button = (JButton)focusEvent.getSource();
         button.selectAll();
      }
   }
);

Author

Commented:
thanks yongsing, this is very close. i only had to change a little bit of code

it looks now like
JTextField textField = new JTextField(8);

textField.addFocusListener
      (
        new FocusListener()
        {
          public void focusGained(FocusEvent focusEvent)
          {
            JTextField field = (JTextField)focusEvent.getSource();
            field.selectAll();
          }
          public void focusLost(FocusEvent focusEvent){}
        }
      );

i had to add the focus lost function. I would also like to set the initial focus to my first textfield. is this possible?

Commented:
You can use the FocusAdapter instead of FocusListener. In this case, you don't have to add the focusLost()
method.

JTextField textField = new JTextField(8);
textField.addFocusListener(
   new FocusAdapter() {
      public void focusGained(FocusEvent focusEvent) {
         JTextField field = (JTextField)focusEvent.getSource();
         field.selectAll();
      }
   }
);

To bring the focus to the desired text field, you can add a window listener. When the window is activated, request the focus to the desired text field.

addWindowListener(
   new WindowAdapter() {
      public void windowActivated(WindowEvent windowEvent) {
         textField.requestFocus();
      }
   }
);

Author

Commented:
yongsing,
my JPanel will not take the addWindowListener function. i tried doing addContainerListener, but couldnt get that to work either. any help?

Commented:
The JPanel must be contained in a JDialog or JFrame, right? Then call JDialog.addWindowListener() or JFrame.addWindowListener().
Ovi

Commented:
Just use textFieldX.requestFocus() on the creation  (constructor, initialization) of your panel (after textfieldX was created)

Author

Commented:
i tried both of these and neither are working. Yongsing, i made my JFrame static, and then passed it to the class that creates this particular panel. Once i had finished creating all my JTextFields, i added the windowlistener and did as you said. but i went and ran it, nothing happened. so i ran debug, and debug skipped right over that line of code. so then i tried stepping into it, and it threw the class loader class not found exception.

Ovi, i tried putting a request focus at the end of my constructor, but that did nothing either.  the other part works once i set the focus using the mouse, where the focus selects all when i tab, but the initial tab is not set.
Ovi

Commented:
try then textFieldX.requestDefaultFocus()

Author

Commented:
that doesnt do it either...
here is the code from my file. i have a vector of JTextFields, and i want the zero'th element to have focus first.



package gui;

import fileData.ReadData;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import dataStructure.Game;
import java.util.Vector;
/**
 * Title:        Standings and Schedule
 * Description:
 * Copyright:    Copyright (c) 2001
 * Company:
 * @author Eric Pastoor
 * @version 1.0
 */

public class ShowGame implements ActionListener{
  private ReadData readin;
  public JPanel   mainPanel;
  private JPanel  center,
                  north,
                  south;
  private Vector  v_TField;
  private Vector  v_TFieldFocus;
  private JButton b_ok,
                  b_cancel;

  private int codeWeekNum;
  boolean badWeek = false;

  public ShowGame(ReadData dataclass, Integer gameNumber, JButton ok, JButton cancel, JFrame mainFrame)
  {
    readin = dataclass;
    b_ok = ok;
    b_cancel=  cancel;
    codeWeekNum = gameNumber.intValue()-1;

    int numColumns = 7;

    b_ok.addActionListener(this);

    center = new JPanel(new GridLayout(13, numColumns));
    north = new JPanel(new FlowLayout());
    mainPanel = new JPanel(new BorderLayout());
    south = new JPanel(new FlowLayout());

    v_TField = new Vector();
    v_TFieldFocus = new Vector();

    north.add(new JLabel("Editing Game Number: " + gameNumber.toString()));

    south.add(b_ok);
    south.add(b_cancel);

    mainPanel.add(center,BorderLayout.CENTER);
    mainPanel.add(north, BorderLayout.NORTH);
    mainPanel.add(south, BorderLayout.SOUTH);

    int i=0;
    while(i<readin.vectorClass.v_NoGames.size())
    {
      if(gameNumber.equals ((Integer)readin.vectorClass.v_NoGames.elementAt(i)))
      {
        badWeek = true;
      }
      i++;
    }
    if(!badWeek)
    {
      AddTeams(codeWeekNum, numColumns);
      for(int j=0; j<4; j++)AddBlanks(numColumns);
    }
    else
    {
      center.add(new JLabel("You have chosen a day when there are no games scheduled."));
    }
    ((JTextField)v_TField.elementAt(0)).requestDefaultFocus();
    /*mainFrame.addWindowListener
    (
      new WindowAdapter()
      {
        public void windowActivated(WindowEvent windowEvent)
        {
          ((JTextField)v_TField.elementAt(6)).requestFocus();
        }
      }
    );*/

  }
  private void AddTeams(int week, int numColumns)
  {

  int num=2;
  int textFieldCtr=0;
  for(int m=0;m<3; m++)
  {
    for(int i=num-2; i < num; i++)
    {
      Game temp = readin.vectorClass.GetGame(week, i);

      JLabel team1 = new JLabel(readin.vectorClass.GetTeamName(temp.getTeam1()));
      team1.setHorizontalAlignment(SwingConstants.CENTER);
      JLabel at = new JLabel("  at  ");
      at.setHorizontalAlignment(SwingConstants.CENTER);
      JLabel team2 = new JLabel(readin.vectorClass.GetTeamName(temp.getTeam2()));
      team2.setHorizontalAlignment(SwingConstants.CENTER);

      v_TField.addElement(new JTextField(temp.getT1Score().toString()));
      ((JTextField)v_TField.lastElement()).addFocusListener
      (
        new FocusListener()
        {
          public void focusGained(FocusEvent focusEvent)
          {
            JTextField field = (JTextField)focusEvent.getSource();
            field.selectAll();
          }
          public void focusLost(FocusEvent focusEvent){}
        }
      );

      v_TField.addElement(new JTextField(temp.getT2Score().toString()));
      ((JTextField)v_TField.lastElement()).addFocusListener
      (
        new FocusListener()
        {
          public void focusGained(FocusEvent focusEvent)
          {
            JTextField field = (JTextField)focusEvent.getSource();
            field.selectAll();
          }
          public void focusLost(FocusEvent focusEvent){}
        }
      );
      center.add(team1);
      center.add(at);
      center.add(team2);
      if((i+1) != num)
      {
        center.add(new JLabel(""));
      }
    }
    for(int j=textFieldCtr; j < 4+textFieldCtr; j+=2)
    {

      center.add((JTextField)v_TField.elementAt(j));
      center.add(new JLabel(""));
      center.add((JTextField)v_TField.elementAt(j+1));
      if((j+2) != 4+textFieldCtr)
      {
        center.add(new JLabel(""));
      }
    }
    textFieldCtr+=4;
    num+=2;
    AddBlanks(numColumns);
  }

  }
  private void AddBlanks(int numColumns)
  {
    for(int i=0; i<numColumns; i++)
    {
      center.add(new JLabel(""));
    }
  }
  public void actionPerformed(ActionEvent event)
  {
    Object object = event.getSource();
    if(object == b_ok && badWeek==false)
    {
      int gameNum=0;
      for(int i=0; i<readin.vectorClass.ReturnNumberOfTeams(); i+=2)
      {
        Integer t1Score = new Integer(((JTextField)v_TField.elementAt(i)).getText());
        Integer t2Score = new Integer(((JTextField)v_TField.elementAt(i+1)).getText());
        readin.vectorClass.SetScore(codeWeekNum, gameNum, t1Score.intValue(), t2Score.intValue());
        gameNum++;
      }

    }
  }

}
Ovi

Commented:
I will try'it tomorrow, now I must leave the office.
Commented:
Because of your many dependencies I've cannot test your code. You are using inside the ShowGame class objects from your custom package. I've modified a little so will extend JFrame. Try'it, on my computer works fine!

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

/**
* Title:        Standings and Schedule
* Description:
* Copyright:    Copyright (c) 2001
* Company:
* @author Eric Pastoor
* @version 1.0
*/

public class ShowGame extends JFrame {
  JTextField[] fields = new JTextField[10];
  JButton[] buttons = new JButton[10];

  public ShowGame() {
    JPanel fieldsPanel = new JPanel();
    fieldsPanel.setLayout(new GridLayout(2, 5));
    JPanel buttonsPanel = new JPanel();
    buttonsPanel.setLayout(new GridLayout(2, 5));

    for(int i = 0; i<fields.length; i++) {
      fields[i] = new JTextField("Field " + i);
      fieldsPanel.add(fields[i]);

      buttons[i] = new JButton("Focus on " + i);
      buttons[i].addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
          Object o = ae.getSource();
          for(int i = 0; i<buttons.length; i++)
            if(buttons[i].equals(o)) {
              fields[i].requestFocus();
              fields[i].selectAll();
              break;
            }
        }
      });
      buttonsPanel.add(buttons[i]);
    }
    getContentPane().setLayout(new GridLayout(2, 1));
    getContentPane().add(fieldsPanel);
    getContentPane().add(buttonsPanel);
  }

  public static void main(String[] args) {
    ShowGame sg = new ShowGame();
    sg.setSize(600, 400);
    sg.setLocation(200, 200);
    sg.setVisible(true);
  }
}

Author

Commented:
thanks, that helped figure it out.

Explore More ContentExplore courses, solutions, and other research materials related to this topic.