Forum Stats

  • 3,855,563 Users
  • 2,264,523 Discussions
  • 7,906,067 Comments

Discussions

Keyboard focus within Applet

843807
843807 Member Posts: 46,582
edited Oct 22, 2002 12:41PM in Java Applet Development
I have an applet that can run in a browser or as an application. The applet has a number of components in which the user can enter information (such as a JTextField). When I run the applet as an application outside of a browser the keyboard focus works as expected, focus is in the first JTextField and the tab key will move from one field to the next. When I run the applet from the browser, focus is not in any of the JTextFields and if I position to a JTextField the tab key does not move to the next field. I have tried the requestFocus call from the applet init code and from the components with no luck. Can anyone tell me what is required?

I have tried it on both Netscape 6.x and IE 6.0.

Thanks

Comments

  • 843807
    843807 Member Posts: 46,582
    This works for me:
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Focus extends Applet implements KeyListener {
    	Button button;
    	TextField field;
    	public void init() {
    		button = new Button("Push Me");
    		field = new TextField("Type me");
    		button.addKeyListener(this);
    		field.addKeyListener(this);
    		add(button);
    		add(field);
    	}
    	public void keyPressed(KeyEvent e) {
    		if (e.getKeyCode() == KeyEvent.VK_TAB) {
    			Component comp = (Component)e.getSource();
    			comp.transferFocus();
    		}
    	}
    	public void keyReleased(KeyEvent e) {}
    	public void keyTyped(KeyEvent e) {}
    }
    But then again, even without all that KeyEvent mess I had no problems with focus. Hope it works for you though.
  • 843807
    843807 Member Posts: 46,582
    I tried the code but it did not seem to help. I suspect it is due to the components being added.

    The code is as follows (or at least a summary):
    public class Client extends JApplet {
        public Client() {
            MyTopPanel myTopPanel = new MyTopPanel();
            this.getContentPane().add(myTopPanel);
        }
    }
    
    public class MyTopPanel extends JPanel {
        public MyTopPanel() {
             LeftPanel leftPanel = new LeftPanel();
             CenterPanel centerPanel = new CenterPanel();
             this.add(leftPanel,BorderLayout.WEST);
             this.add(centerPanel,BorderLayout.CENTER);
        }
    }
    
    public class CenterPanel extends JPanel {
        public CenterPanel() {
            JTextField test = new JTextField(10);
            test.requestFocus();
            this.add(test);
            JTextField second = new JTextField(10);
            this.add(second);
        }
    }
This discussion has been closed.