JTextField focus

I have a problem with the focus of a JTextField in a JApplet. Why? Here is my code:
class MyPanel extends JPanel {
    ImageIcon imageIcon;
    Image image;
    public MyPanel(Image tiledBackgroundImage) {
        setOpaque(false);
        setLayout(new BorderLayout());
        imageIcon = new ImageIcon(tiledBackgroundImage);
        image = imageIcon.getImage();
    public void paintComponent(Graphics g) {
        for (int x = 0; x < getWidth(); x += image.getWidth(this)) {
            for (int y = 0; y < getHeight(); y += image.getHeight(this))
                g.drawImage(image, x, y, this);
        super.paintComponent(g);
}and in the init() method of my applet I have the following call
setContentPane(new MyPanel(getAppletContext().getImage(new URL(getDocumentBase(), getParameter("backgroundImage")))));However, before I added this code for rendering the background image everything was working well. But after I added it, the JTextFields started to reject focus; when I click on them with the mouse I see a fast blink and then focus is lost again. Why is this so?

Hi,
you could use focus listener..
void focusGained(FocusEvent e)
void focusLost(FocusEvent e)
or you could also check with hasFocus() which returns boolean ....
ramesh

Similar Messages

  • JTextField focus problems in JApplet

    I have a JApplet like this:
    public class AppletLogin extends JApplet {
    public void init() {
    this.setSize(new Dimension(400,300));
    this.getContentPane().setLayout(new FlowLayout());
    this.getContentPane().add(new JTextField(12));
    this.getContentPane().add(new JTextField(12));
    The first problem I have is that both JTextField don't show the cursor if you click in them, they also don't show selected text. If you select another window and then you select back the browser, the cursor appears.
    The second problem is that sometimes, if the cursor appears in the first JTextField and with the TAB or with the mouse you set the focus on the second JTextField, then you can't focus back to the first JTextField. This second problem disappears if you add "this.requestFocus()" in init.
    This behaviour is shown in Windows NT 4.0 and 98 with Netscape 4.7 and 6.2.
    I don't have this problem in Windows 2000 - Netscape 4.7 / 6.2 and Linux - Netscape 6.2.
    The Plugin is 1.3.1_01a and 1.3.1_02.
    I think I have the same problem explained in bug 4186928 but with a JApplet. I have tried the "dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_ACTIVATED))" workaround, using the 'SwingUtilities.getWindowAncestor(this)' Window, but it doesn't
    work.
    Any suggestions to solve the first problem? Should I submit a bug?

    Of course. Here is the original code. I have only removed 'imports' from other classes of the project used for localization and image loading.
    If you want me to translate for you the Spanish comments to English, please tell me.
    This is the code as is now. I have already tried 'requestFocus' and 'grabFocus' even inside a MouseListener attached to 'usuario' (user) and 'clave' (passwd), with no success.
    This code works fine with 1.2.2 plug-in on any OS and with 1.3.1_02 plug-in on Windows 2000 and Linux.
    But with 1.3.1_02 plug-in under Windows 98/NT4.0 and Netscape 4.7/6.2 the focus is crazy. Our customer uses Windows NT 4.0.
    This panel is for user and passwd validation. We use it attached to an JApplet. It has some methods to attach ActionListener to it. It also has a KeyListener to capture 'intro' events. Thats all.
    package project.pkg
    import java.util.TooManyListenersException;
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.event.KeyListener;
    import java.awt.event.KeyEvent;
    import java.awt.event.ComponentAdapter;
    import java.awt.event.ComponentEvent;
    import javax.swing.border.EmptyBorder;
    // import of other.project.pkg
    // import of other.project.pkg
    import javax.swing.*;
    import java.awt.*;
      * Panel de acceso a la aplicaci�n.
      * @version  $Revision: 1.8 $
    public class PanelAcceso extends JRootPane {
       // Marca de revision. ///////////////////////////////
       private final static String VERSION = "@(#) $Id: PanelAcceso.java,v 1.8 2001/05/08 15:55:46 user Exp $";
       /** Campo usuario */
       private JTextField usuario;
       /** Campo clave */
       private JTextField clave;
       /** Panel de los controles */
       private JPanel controles;
       /** Panel auxiliar marco para controles. */
       private JPanel marco;
       /** ActionListener para notificaci�n de intro. de usuario y passwd */
       private ActionListener entrarActionListener = null;
        * Construye un panel de acceso.
       public PanelAcceso() {
         JLabel portada = new JLabel(/*HERE goes an ImageIcon*/);
         portada.setHorizontalAlignment( SwingUtilities.CENTER);
         portada.setVerticalAlignment( SwingUtilities.CENTER);
         getContentPane().setLayout( new BorderLayout());
         getContentPane().add( portada, BorderLayout.CENTER);
         getContentPane().setBackground( Color.white);
         controles = new JPanel();
         controles.setLayout(new GridLayout(4,2,5,5));
         controles.setOpaque(false);
         controles.add( new JLabel("Ver. 2.5.1"));
         controles.add(Box.createHorizontalGlue());
         controles.add(Box.createHorizontalGlue());
         controles.add(Box.createHorizontalGlue());
         controles.add( new JLabel("User") );
         usuario = new JTextField( 12);
         usuario.addKeyListener(keyListener);
         controles.add( usuario);
         controles.add( new JLabel("Passwd") );
         clave = new JPasswordField( 12);
         clave.addKeyListener(keyListener);
         controles.add( clave);
         // Panel auxiliar marco para controles.
         marco = new JPanel(new FlowLayout(FlowLayout.RIGHT));
         marco.setOpaque(false);
         marco.add(controles);
         setGlassPane(marco);
         // Listener para fijar el borde de marco seg�n cambie de
         // tama�o el panel.
         marco.addComponentListener( new ComponentAdapter() {
           public void componentResized(ComponentEvent e) {
             changeEmptyBorder();
           public void componentShown(ComponentEvent e) {
             changeEmptyBorder();
         marco.setVisible(true);
        * Devuelve el usuario introducido.
       public String getUser() {
         return usuario.getText();
        * Devuelve la contrase�a introducida.
       public String getPasswd() {
         return clave.getText();
        * Limpia el panel de acceso.
       public void limpiar() {
         clave.setText("");
         usuario.setText("");
        * A�ade un listiener a los eventos de
        * petici�n de acceso dado un usuario y
        * una contrase�a.
        * @throws TooManyListenersException si ya se ha a�adido un listener.
       public void addEntrarListener(ActionListener l) throws TooManyListenersException {
         if ((entrarActionListener != null) && (entrarActionListener != l))
           throw new TooManyListenersException("Solo se admite un listener");
         else
           entrarActionListener = l;
        * Borra un listener.
       public void removeEntrarListener(ActionListener l) {
         if (entrarActionListener == l)
           entrarActionListener = null;
         else
           throw new IllegalArgumentException("Intento de borrar un listener no a�adido");
        * Borra todos los listeners.
       public void removeEntrarListeners() {
         entrarActionListener = null;
        * Instancia privada de KeyListener para capturar
        * los 'enter' en los campos de usuario y passwd.
       private KeyListener keyListener = new KeyListener() {
          * Method to handle events for the KeyListener interface.
          * @param e KeyEvent
         public void keyPressed(KeyEvent e) {
           if (e.getKeyCode() != KeyEvent.VK_ENTER)
             return;
           if ((e.getSource() == usuario) )
             clave.requestFocus();
           else {
             requestFocus(); // Se evitan varias pulsaciones seguidas.
             if (entrarActionListener != null)
               entrarActionListener.actionPerformed(new ActionEvent(this, 0, ConstantesXigus.ACCION_ENTRAR));
         /** Method to handle events for the KeyListener interface. */
         public void keyReleased(KeyEvent e) {}
         /** Method to handle events for the KeyListener interface. */
         public void keyTyped(KeyEvent e) {}
        * Ajusta el borde del marco de controles para que aparezcan centrados.
       private void changeEmptyBorder() {
         Dimension dimMarco   = marco.getSize();
         Dimension dimInterno = controles.getPreferredSize();
         int altoBorde  = dimMarco.height - dimInterno.height;
         int anchoBorde = (dimMarco.width - dimInterno.width)/2;
         marco.setBorder( new EmptyBorder( (int)(altoBorde * 0.75), anchoBorde, (int)(altoBorde * 0.25), anchoBorde));
    }Thank you very much for your help

  • Jtextfield focus after validation

    I have a JFrame which contains several jtextField objects. There is also one button. Upon clicking of this button I check if any of these jtextfield is null. If it is I show a message box. At this point I want to focus on the first null jtextfield. However when I try to get focus, nothing happens... Below is the code of the button I use. As you can see I have tried to use SwingUtilities.invokeLater(new Runnable() and requestFocus() and also grabFocus(). But none is working... How can I achieve this?
      private void jbtnSaveActionPerformed(java.awt.event.ActionEvent evt) {                                        
    // TODO add your handling code here:
            if (txtUser.getText()+"" == "" ) {
                txtUser.requestFocus();
            else if (jtxtPass2.getText()+"" == "" ){
                System.out.println("I am here");
                SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                jtxtPass2.requestFocus();
                jtxtPass2.grabFocus();
    //            jtxtPass2.requestFocus();
            else if (txtDBName.getText()+"" == ""){
                txtDBName.requestFocus();
            else if (txtPort.getText()+"" == ""){
                txtPort.requestFocus();
            else if(txtMachine.getText()+"" == ""){
                txtMachine.requestFocus();
            else      { 
            jframeload.setDBVariables(txtMachine.getText() + "", Integer.parseInt(txtPort.getText() + ""), txtDBName.getText() + "", txtUser.getText() + "", jtxtPass2.getText() + "");
            this.dispose();
        }       

    After adding the txtUser.getText().trim().length() == 0 it now works. I guess the check was failing and no focus was being requested. Now my code looks like
    if (txtUser.getText().trim().length() == 0 ) {
                txtUser.requestFocus();
                jframeload.jMessage.append("\n Username is a required field. " + getCurrDate());
                jframeload.jMessage.setCaretPosition( jframeload.jMessage.getDocument().getLength() );
            }

  • JTextField Focus...Please Help!

    Hello,
    I have an issue which i hope someone may be able to help me with. What i am trying to do i think is simple but i am still not up to speed on getFocus events so i hope somebody will be able to aid me.
    I have two text fields and one button on a form. When a text field is selected and the button pressed i expect to see a letter appear in the text field dep(String) depending on which one has the focus. However i have not been able to fully achieve this funcionality.
    The code I have so far:
    private void button1_actionPerformed(ActionEvent e)
         if (gf.WHEN_FOCUSED == 0){
           //gf.setFocusable(true);
             gf.gotFocus();
             txt2 = txt2 + txt;
              gf.setText(txt2);
           else if(tf.WHEN_FOCUSED == 0){
             //  tf.setFocusable(true);
                 tf.gotFocus();
                 txt2 = txt2 + txt;
                 tf.setText(txt2);
      }Could someone help me with this?
    Thanks

    Write your own TextAction. The TextAction keeps track of the last text component to have focus. Here is a simple example:
    JButton selectAll = new JButton( new SelectAll() );
    class SelectAll extends TextAction
         public SelectAll()
              super("Select All");
         public void actionPerformed(ActionEvent e)
              JTextComponent component = getFocusedComponent();
              component.selectAll();
    }

  • How to have jtextfield focus enabled after window loading

    Hi
    Can I know how a JTextField can have cursor in it after the window it consists is loaded?
    Tried using the requestFocus(), but it did not work even after
    isFocusable() returned true.
    Could I get a whole piece of working code if possible, to see what interfaces my class should implement and what methods have to be overridden.
    More:
    I have a JTextArea(not editable) , JTextField and a JButton in the frame.
    Thanks
    Reddy

    hi try this code
    import javax.swing.*;
    public class exam1 extends JFrame
         public exam1()
              setSize(450,500);
              JTextField tx1= new JTextField(15);
              tx1.requestFocus();
              JPanel pnl= new JPanel();
              pnl.add(tx1);
              getContentPane().add(pnl);
         public static void main(String arg[])
              exam1 ex = new exam1();
              ex.setVisible(true);
              //ex.show();
    }Cheers
    jofin

  • JTextField Focus is not comming

    Hi
    I have 2 JTextField(userName and password).I am entering wrong username and password .It goes to server and rsponse come with worning "Wrong input".Then I am entering the username again and after that when i Press the tab key .the curser come to the middle portion of the password field and i am unble to write to the password field at that time.When I click on the password field in mouse the curser comes to the start position and i able to write at that time.Any body can tell me why the curser comes to the middle of the password field when i am pressing tab key.
    thanks
    srikant

    have you tried your code with on of the latest jdk 5.0 updates (jdk 5.0_14 for example) ?

  • JTextField Focus Lost Behaviour

    Hi all,
    I have one TextField beside one hlp button , when i enter the value in the textfiled and press tab or press the hlp button same validation
    should popup ......here my problem is at first time when i press the
    hlp button the valiation is not getting but the window was get opened.
    Before the window opening validation also should popup .......
    can any body help me ...pls
    my code is like this
    compradorDdfTf.addKeyListener(new KeyAdapter() {
                   public void keyPressed(KeyEvent e) {
    if (e.getKeyCode() == KeyEvent.VK_TAB) {
    //my code
    public void keyTyped(KeyEvent e) {
                        compradorDdfbool = true;
    Regards,
    Rohit

    You have been asked multiple times to respond to all of you previous posting when you receive help. You still haven't learned how to do this.
    You have been asked several time to use the "Code Formatting Tags" when posting code. You still aren't doing this.
    Now you've added multi-posting to things you shouldn't be doing. If you want to change your question then you can "edit" you posting until someone replies to the posting.
    Not only that you where given an answer to this question in your last posting.
    I'm not will to help someone who can't learn the basics of using the forum effectively. You are still on your own.

  • JTextField input check (errorDialog if invalid) & JComboBox Focus

    I have a JTextfield which does an input check when the JTextField focus listener's focusLost method is called.
    If I loose focus by clicking in on a JComboBox. The check gets done ok and focus is returned appropriately to the JTextField without any problems.
    But if I try to show an errorDialog when the input is incorrect, the focus is returned to the JTextField without any problems, but the JComboBox remains highlighted as though it is still selected!
    I am using sdk 1.4... on a linux box. does anyone know why this happens? and can anyone provide a clean solution to this?
    Thanx,
    Diego Paloschi.

    Hello Kleopatra,
    Here's a little demo:
    import javax.swing.*;
    import javax.swing.event.*;
    public class Debug extends JPanel
    private JTextField t1;
    private JComboBox c1;
    private T1Verifier t1Verifier;
    public void init()
         t1 = new JTextField("20", 10);
         t1.setInputVerifier(new T1Verifier(this));
         String[] s = {"v1","v2","v3"};
         c1 = new JComboBox(s);
         add(t1);
         add(c1);
    public static void main(String s[])
         Debug d = new Debug();
         d.init();
         JFrame f = new JFrame("Debug");
         f.getContentPane().add(d);
         f.setSize(300,300);
         f.setVisible(true);
    class T1Verifier extends InputVerifier
    private Debug debug;
    public T1Verifier(Debug debug)
         this.debug = debug;
    public boolean verify(JComponent input)
         JTextField tf = (JTextField) input;
         float value = Float.parseFloat(tf.getText());
         boolean inRange = (value >= 0) && ( value <= 10);
         return inRange;
    public boolean shouldYieldFocus(JComponent input)
         boolean valid = super.shouldYieldFocus(input);
         JTextField tf = (JTextField) input;
         if ( !valid ) {
         tf.requestFocus();
         JOptionPane d = new JOptionPane();
         d.showMessageDialog(debug, "Out Of Range.", "ERROR" , JOptionPane.ERROR_MESSAGE);
         return valid;
    Even if u comment out the JOptionPane and just make the inputverifier return control to the textfield it still doesn't work! What am I missing? Or how would u doi it?

  • 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);
    }

  • Editable JComboBox in JTable focus issue

    Please look at the sample code below.
    I am using a JComboBox as the editor for a column in the table. When a cell in that column is edited and the user presses enter, the cell is no longer in edit mode. However, the focus is now set on the next component in the scrollpane (which is a textfield).
    If I don't add the textfield and the the table is the only component in the scroll pane, then focus correctly remains on the selected cell.
    When the user exits edit mode, I'd like the table to have focus and for the cell to remain selected. How can I achieve this?
    thanks,
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.util.Calendar;
    import java.util.GregorianCalendar;
    import javax.swing.plaf.basic.*;
    import java.awt.Component;
    import javax.swing.JComboBox;
    import java.util.EventObject;
    import java.awt.event.*;
    import javax.swing.event.*;
    public class TableComboBoxTest extends JFrame {
         protected JTable table;
         public TableComboBoxTest() {
              Container pane = getContentPane();
              pane.setLayout(new BorderLayout());
              MyTableModel model = new MyTableModel();
              table = new JTable(model);
              table.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
              table.setSurrendersFocusOnKeystroke(true);
              TableColumnModel tcm = table.getColumnModel();
              TableColumn tc = tcm.getColumn(MyTableModel.GENDER);
              tc.setCellEditor(new MyGenderEditor(new JComboBox()));
              tc.setCellRenderer(new MyGenderRenderer());
              JScrollPane jsp = new JScrollPane(table);
              pane.add(jsp, BorderLayout.CENTER);          
              pane.add(new JTextField("focus goes here"), BorderLayout.SOUTH);
         public static void main(String[] args) {
              TableComboBoxTest frame = new TableComboBoxTest();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setSize(500, 300);
              frame.setLocationRelativeTo(null);
              frame.setVisible(true);
         public class MyTableModel extends AbstractTableModel {
              public final static int FIRST_NAME = 0;
              public final static int LAST_NAME = 1;
              public final static int DATE_OF_BIRTH = 2;
              public final static int ACCOUNT_BALANCE = 3;
              public final static int GENDER = 4;
              public final static boolean GENDER_MALE = true;
              public final static boolean GENDER_FEMALE = false;
              public final String[] columnNames = {
                   "First Name", "Last Name", "Date of Birth", "Account Balance", "Gender"
              public Object[][] values = {
                        "Clay", "Ashworth",
                        new GregorianCalendar(1962, Calendar.FEBRUARY, 20).getTime(),
                        new Float(12345.67), "three"
                        "Jacob", "Ashworth",
                        new GregorianCalendar(1987, Calendar.JANUARY, 6).getTime(),
                        new Float(23456.78), "three1"
                        "Jordan", "Ashworth",
                        new GregorianCalendar(1989, Calendar.AUGUST, 31).getTime(),
                        new Float(34567.89), "three2"
                        "Evelyn", "Kirk",
                        new GregorianCalendar(1945, Calendar.JANUARY, 16).getTime(),
                        new Float(-456.70), "One"
                        "Belle", "Spyres",
                        new GregorianCalendar(1907, Calendar.AUGUST, 2).getTime(),
                        new Float(567.00), "two"
              public int getRowCount() {
                   return values.length;
              public int getColumnCount() {
                   return values[0].length;
              public Object getValueAt(int row, int column) {
                   return values[row][column];
              public void setValueAt(Object aValue, int r, int c) {
                   values[r][c] = aValue;
              public String getColumnName(int column) {
                   return columnNames[column];
              public boolean isCellEditable(int r, int c) {
                   return c == GENDER;
         public class MyComboUI extends BasicComboBoxUI {
              public JList getList()
                   return listBox;
         public class MyGenderRenderer extends DefaultTableCellRenderer{
              public MyGenderRenderer() {
                   super();
              public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
                        boolean hasFocus, int row, int column) {
                   JComboBox box = new JComboBox();
                   box.addItem(value);
                   return box;
         public class MyGenderEditor extends DefaultCellEditor  { // implements CaretListener {
              protected EventListenerList listenerList = new EventListenerList();
              protected ChangeEvent changeEvent = new ChangeEvent(this);
              private JTextField comboBoxEditorTField;
              Object newValue;
              JComboBox _cbox;
              public MyGenderEditor(JComboBox cbox) {
                   super(cbox);
                   _cbox = cbox;
                   comboBoxEditorTField = (JTextField)_cbox.getEditor().getEditorComponent();
                   _cbox.addItem("three");
                   _cbox.addItem("three1");
                   _cbox.addItem("three2");
                   _cbox.addItem("One");
                   _cbox.addItem("two");
                   _cbox.setEditable(true);
                   _cbox.addActionListener(new ActionListener() {
                        public void actionPerformed(ActionEvent event) {
                             System.out.println("\nactionPerformed ");
                             fireEditingStopped();
              public void addCellEditorListener(CellEditorListener listener) {
                   listenerList.add(CellEditorListener.class, listener);
              public void removeCellEditorListener(CellEditorListener listener) {
                   listenerList.remove(CellEditorListener.class, listener);
              protected void fireEditingStopped() {
                   System.out.println("fireEditingStopped called ");
                   CellEditorListener listener;
                   Object[] listeners = listenerList.getListenerList();
                   for (int i = 0; i < listeners.length; i++) {
                        if (listeners[i] instanceof CellEditorListener) {
                             System.out.println("calling editingStopped on listener....................");                    
                             listener = (CellEditorListener) listeners;
                             listener.editingStopped(changeEvent);
              protected void fireEditingCanceled() {
                   System.out.println("fireEditingCanceled called ");
                   CellEditorListener listener;
                   Object[] listeners = listenerList.getListenerList();
                   for (int i = 0; i < listeners.length; i++) {
                        if (listeners[i] instanceof CellEditorListener) {
                             listener = (CellEditorListener) listeners[i];
                             listener.editingCanceled(changeEvent);
              public void cancelCellEditing() {
                   System.out.println("cancelCellEditing called ");
                   fireEditingCanceled();
              public void addNewItemToComboBox() {
                   System.out.println("\naddNewItemToComboBox called ");
                   // tc - start
                   String text = comboBoxEditorTField.getText();
                   System.out.println("text = "+text);                    
                   int index = -1;
                   for (int i = 0; i < _cbox.getItemCount(); i++)
                        String item = ((String)_cbox.getItemAt(i));
                        System.out.println("item in cbox = "+item);
                        if (item.equals(text))
                             System.out.println("selecting item now...");                              
                             index = i;
                             _cbox.setSelectedIndex(index);
                             break;
                   if (index == -1)
                        _cbox.addItem(text);
                        int count = _cbox.getItemCount();
                        _cbox.setSelectedIndex(count -1);
              public boolean stopCellEditing() {
                   System.out.println("stopCellEditing called ");
                   fireEditingStopped();
                   _cbox.transferFocus();
                   return true;
              public boolean isCellEditable(EventObject event) {
                   return true;     
              public boolean shouldSelectCell(EventObject event) {
                   return true;
              public Object getCellEditorValue() {
                   System.out.println("- getCellEditorValue called returning val: "+_cbox.getSelectedItem());
                   return _cbox.getSelectedItem();
              public Component getTableCellEditorComponent(JTable table, Object value,
                        boolean isSelected, int row, int column) {
                   System.out.println("\ngetTableCellEditorComponent "+value);
                   String text = (String)value;               
                   for (int i = 0; i < _cbox.getItemCount(); i++)
                        String item = ((String)_cbox.getItemAt(i));
                        System.out.println("item in box "+item);
                        if (item.equals(text))
                             System.out.println("selecting item now...");     
                             _cbox.setSelectedIndex(i);
                             break;
                   return _cbox;

    I was using java 1.5.0_06 in my application and I had this problem
    When I upgraded to java 1.6.0_01, I no longer had this issue.
    This seems to be a bug in 1.5 version of Java that has been fixed in 1.6
    thanks,

  • Focus of JWindow in Solaris OS urgent!...

    In my application the whole Guis lies on an window when this application is opened my JWindow is not getting the Focus in Solaris OS even though i give requestFocus() please help somebody

    This is kind of strange, I use this technique myself with J2SDK 1.3.1 and Solaris 8. I exteded the sample code:
    The extended source of the WindowListener again.
    import javax.swing.*;
    import java.awt.event.*;
    public class GrabFocusWindowAdapter extends WindowAdapter
    private JComponent component;
    public GrabFocusWindowAdapter(JComponent component)
    this.component = component;
    public void windowOpened(WindowEvent event)
    setFocus(event);
    public void windowIsClosing(WindowEvent event)
    setFocus(event);
    public void setFocus(WindowEvent event)
    if (component != null && component.isEnabled())
    component.requestFocus();
    The dialog classes source is as follows (when the dialog appears, the "focused" field should have the focus (always)):
    import javax.swing.*;
    public class DetailsDialog extends JDialog
    public DetailsDialog(JFrame parent)
    super(parent, "Title");
    JTextField focused = new JTextField();
    JTextField notFocused = new JTextField();
    getContentPane().setLayout(new BorderLayout());
    getContentPane().add(focused, BorderLayout.NORTH);
    getContentPane().add(notFocused, BorderLayout.SOUTH);
    pack();
    setResizable(false);
    addWindowListener(new GrabFocusWindowAdapter(focused));
    }

  • Open and Close OnScreen Keyboard while focus gain on JTextField

    Hi
    I have a Jtextfield when ever I click on textfield I want to open OSK(On Screen Keyboard) of Windows 8 OS and windows 7.
    I tried in below mentioned way to open and close in focus listener focusGained() and focusLost() but it is not working. could some body do needful.
    Opening OSK:
    builder = new ProcessBuilder("cmd /c " + sysroot + " /System32/osk.exe");
    Closing Osk:
    Runtime.getRuntime().exec("taskkill /f /im osk.exe");

    You need to start() the ProcessBuilder and you need to split the command like this:
    builder  = new ProcessBuilder("cmd", "/c", sysroot + " /System32/osk.exe");
    builder.start();
    And naturally you should wrap the call in a new Thread or use an ExecutorService to avoid EDT problems.

  • How to capture the event on changing focus from a JTextField?

    Hi All,
    I have got a problem...
    I want to do something (say some sort of validations/calculations) when I change the focus by pressing tab from a JTextField. But I am not able to do that.
    I tried with DocumentListener (jtf01.getDocument().addDocumentListener(this);). But in that case, it's calling the event everytime I ke-in something in the text field. But that's not what I want. I want to call that event only once, after the value is changed (user can paste a value, or even can key-in).
    Is there any way for this? Is there any method (like onChange() in javascript) that can do this.
    Please Help me...
    Regards,
    Ujjal

    Hi Michael,
    I am attaching my code. Actual code is very large containing 'n' number of components and ActionListeners. I am attaching only the relevant part.
    //more codes
    public class PaintSplitDisplay extends JApplet implements ActionListener
         JFrame jf01;
         JPanel jp01;
         JTextField jtf01, jtf02;
         //more codes
         public void start()
              //more codes
             jtf01 = new JTextField();
              jtf01.setPreferredSize(longField);
              jtf01.setFont(new Font("Courier new",0,12));
              jtf01.setInputVerifier(new InputVerifier(){public boolean verify(JComponent input)
                   //more codes
                   System.out.print("updating");
                   jtf02.setText("updated value");
                   System.out.print("updated");
                   return true;
              //more codes
              jtf02 = new JTextField();
              jtf02.setPreferredSize(mediumField);
              jtf02.setEditable(false);
              jp01.add(jtf02, gbc);
              //more codes
              jf01.add(jp01);
              jf01.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              jf01.setVisible(true);
              //more codes
         public static void main(String args[])
              PaintSplitDisplay psp = new PaintSplitDisplay();
              psp.start();
         public void actionPerformed(ActionEvent ae)
              //more codes
    }As you can see I want to update the second JTextField based on some calculations. That should happen when I change the focus from my frist JTextField. I have called jtf02.setText() method inside InputVerifier. But it's giving error...
    Please suggest...
    Ujjal

  • Problem with focus and selecting text in jtextfield

    I have problem with jtexfield. I know that solution will be very simple but I can't figure it out.
    This is simplified version of situation:
    I have a jframe, jtextfield and jbutton. User can put numbers (0-10000) separated with commas to textfield and save those numbers by pressing jbutton.
    When jbutton is pressed I have a validator which checks that jtextfield contains only numbers and commas. If validator sees that there are invalid characters, a messagebox is launched which tells to user whats wrong.
    Now comes the tricky part.
    When user presses ok from messagebox, jtextfield should select the character which validator said was invalid so that user can replace it by pressing a number or comma.
    I have the invalid character, but how can you get the focus to jtextfield and select only the character which was invalid?
    I tried requestFocus(), but it selected whole text in jtextfield and after that command I couldn't set selected text. I tried with commands setSelectionStart(int), setSelectionEnd(int) and select(int,int).
    Then I tried to use Caret and select text with that. It selected the character I wanted, but the focus wasn't really there because it didn't have keyFocus (or something like that).
    Is there a simple way of doing this?

    textField.requestFocusInWindow();
    textField.select(...);The above should work, although read the API on the select(...) method for the newer recommended approach on how to do selection.
    If you need further help then you need to create a "Short, Self Contained, Compilable and Executable, Example Program (SSCCE)",
    see http://homepage1.nifty.com/algafield/sscce.html,
    that demonstrates the incorrect behaviour, because I can't guess exactly what you are doing based on the information provided.
    Don't forget to use the "Code Formatting Tags",
    see http://forum.java.sun.com/help.jspa?sec=formatting,
    so the posted code retains its original formatting.

  • How can a JTextField in a Dialog gain focus while mainframe is clicked

    Hi
    I have been trying to develop a 3d application. I have some shapes on a Canvas3D laid on a JFrame.
    I open a new shape dialog after pressing the appropriate button.
    Once the dialog is open I need to select two shapes on canvas for reference hence there are two text fields to show the name of each.
    when I select the first shape the corresponding textfield is being updated.
    Now the Problem
    I place the cursor in the second tex field and click on second shape on canvas.
    I lose focus from text field to canvas.
    Now I am unsure if the second textfield has the focus or is the focus with the first text field. Based on this focus info I can update the text fields.
    I understand that only one field can have focus at a time.
    My doubt is How can the JTextField retain its focus while the components on main window are being clicked.
    The following code is enclosed in a listener that responds to picked shapes.
    if(gooi.getSketchDialog() != null && gooi.getSketchDialog().isShowing()){
                gooi.getPick1().getCanvas().setFocusable(false);
                if(gooi.getSketchDialog().getSelectedPlaneTextField().isFocusOwner()){
                        if( pickResult != null)
                            gooi.getSketchDialog().getSelectedPlaneTextField().setText(pickResult.getNode(PickResult.SHAPE3D).getUserData().toString());
                        else if (pickResult == null){
                            gooi.getSketchDialog().getSelectedPlaneTextField().setText("");
            }Any help is appreciated.
    Thanks in Advance
    Venkat
    Edited by: pushinglimits on Oct 31, 2008 6:52 AM

    Michael
    The text field still loses focus when its containing window is no longer focused.import java.awt.FlowLayout;
    import java.awt.event.FocusEvent;
    import java.awt.event.FocusListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    public class NoFocusTransfer implements FocusListener {
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             @Override
             public void run() {
                new NoFocusTransfer().makeUI();
       public void makeUI() {
          JTextField one = new JTextField(20);
          one.addFocusListener(this);
          JTextField two = new JTextField(20);
          two.addFocusListener(this);
          JFrame frameOne = new JFrame("");
          frameOne.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frameOne.setSize(400, 400);
          frameOne.setLocationRelativeTo(null);
          frameOne.setLayout(new FlowLayout());
          frameOne.add(one);
          frameOne.add(two);
          JButton button = new JButton("Click");
          button.setFocusable(false);
          JFrame frameTwo = new JFrame();
          frameTwo.add(button);
          frameTwo.pack();
          frameTwo.setFocusable(false);
          frameOne.setVisible(true);
          frameTwo.setVisible(true);
       public void focusGained(FocusEvent e) {
          try {
             System.out.println("Focus from: " +
                     e.getOppositeComponent().getClass().getName());
             System.out.println("Focus to: " +
                     e.getComponent().getClass().getName());
          } catch (NullPointerException npe) {
       public void focusLost(FocusEvent e) {
          try {
             System.out.println("Focus from: " +
                     e.getComponent().getClass().getName());
             System.out.println("Focus to: " +
                     e.getOppositeComponent().getClass().getName());
          } catch (NullPointerException npe) {
    }db

Maybe you are looking for

  • Setting Up Multiple iPhones On One iTunes Account

    Our business supplies iPhones to our technicians out in the field and I've set each phone up under the same iTunes account. Can someone please help me out on the below things that I need to be able to manage? I need to be able to back up each iPhone

  • Brand new mac mini won't boot

    I bought a mac mini for my teenaged daughter because the lap top options simply weren't in our price range. I have a high end dell monitor that is about five years old. It hasn't been used regularly so I felt this was a good fit. I was reassured by s

  • Adobe XI trial has stopped my use of previous version of Acrobat reader now that trial is over

    Now that my Trial period is over  of Adobe XI Pro, I cannot use my old Acrobat reader, nor open any of my .pdf files!!!!!!!!!!! Need fix.  Reloading Acrobat reader does not seem to fix this issue.

  • Lumix Raw Files

    I have just purchased a Lumix DMC LX3 camera. Great camera, but the raw files are not yet supported by Lightroom 2 or Camera Raw. Any way around this?

  • Compare folders and output files with same name?

    I'm trying to compare two folders and print only the excel files in folder B that have the same names as the pages files in folder A. I've tried using the completedigitalphotography "compare folders" action, but it will only output files that are of