Sendkey method in Java


I want to make my software interface so user can move the focus from one textfield to another by pressing enter to move focus forward to next field, just as like when press tab key. So in another word, i want to replaced ENTER key code by TAB key code, if in VB programming, usually i use SendKeys “{TAB}” in KeyDown event.

And then here some code that maybe can work as i want to, another way that work it, please info it for me, thanks

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

public class SendKeyTest extends javax.swing.JFrame {

private Dimension d = Toolkit.getDefaultToolkit().getScreenSize();

private javax.swing.JTextField text1;
private javax.swing.JTextField text2;

Robot r;

public SendKeyTest() {
text1 = new javax.swing.JTextField();
text2 = new javax.swing.JTextField();

setTitle( “Test SendKey” );

getContentPane().setLayout( null );
getContentPane().add(text1);
getContentPane().add(text2);

text1.setBounds( 10, 20, 100, 30 );
text2.setBounds( 10, 50, 100, 60 );

try {
r = new Robot();
} catch (AWTException ex) {
ex.printStackTrace(); // for Robot()
}

text1.addKeyListener (new KeyAdapter () {
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
sendKey(KeyEvent.VK_TAB);
}
}
});

text2.addKeyListener (new KeyAdapter () {
public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_ENTER) {
sendKey(KeyEvent.VK_TAB);
}
}
});

setDefaultCloseOperation( javax.swing.WindowConstants.EXIT_ON_CLOSE );
setSize( 360, 360 );
setResizable( false );
setLocation( d.width / 2 – getWidth() / 2, d.height / 2 – getHeight() / 2 );
setVisible( true );
}

private void sendKey(int keyCode) {
r.keyPress(keyCode);
r.keyRelease(keyCode);
r.delay(500); // for you to see the keystroke
}

public static void main( String args[] ) {
SendKeyTest sk = new SendKeyTest();
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: