Today You will learn :
- How to use Inner Class to use Key Events and Mouse Events
- How to cancel key typed event in Java
- How make numeric JTextField
- How to limit the number of characters in JTextField
- consume() method of the KeyListener interface
- Character.isDigit() method and getKeyChar() method
The main things here are the JTextField , KeyEvents , Inner Classes in Java and how to create numeric TextFields in Java and if you want numeric text box in C# Click Here
How to use Inner Classes to Implement KeyEvents?
When i first used inner classes i really avoided them because they a bit complex. But trust me Inner classes are'nt that difficult as they are thought to be. Here's how its done :
- Create a private inner class
- Use the implement keyword to implement the KeyListener interface
- Override all the methods of the interface KeyListener
- Create the Object of the Inner Class in the enclosing Class like that "InnerClass i = outerclassobject.new InnerClass()"(you have to create outer class object first)
- Add the object of inner class to the object of component class which you want to implement KeyEvents for example "JTextField.add(KeyListenerObject)"
Here is the code:
import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
public class NumericBox{
static JTextField tf = new JTextField();
public static void main(String arh[]){
NumericBox g = new NumericBox();
Handle h = g.new Handle();
JFrame f = new JFrame();
JPanel p = new JPanel();
tf.setColumns(5);
tf.addKeyListener(h);
p.add(tf);
f.add(p);
f.setSize(200, 200);
f.setVisible(true);
}//end of main method
private class Handle implements KeyListener{
public void keyTyped(KeyEvent e) {
if(tf.getText().length() == 6)
e.consume();
if(e.getKeyChar() != 13 && !Character.isDigit(e.getKeyChar())
&& e.getKeyChar() != 42 && e.getKeyChar() != 43 //key codes of the keys
&& e.getKeyChar() != 45 && e.getKeyChar() != 46 //you want to enable
&& e.getKeyChar() != 47)
e.consume();
}
public void keyPressed(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}
}//end of inner class
}//end of outer class
0 comments:
Post a Comment