Key listeners
We discuss how keyboard events are handled. As an example, we create a window with one text field, which has a listener to listen to events that are generated by keys. The listener is implemented by an inner class KeyList, which extends the adapter class KeyAdapter. This is the least troublesome solution to program since the KeyListener class contains more methods than those we require: keyTyped, keyReleased and the method that we will override in the inner class, keyPressed. This method is invoked whenever a key is pressed by the user. In our example, it checks whether the delete key has been pressed and then removes the text that is contained in the text field. The delete key is represented by the static constant VK_DELETE, which forms part of the KeyEvent class. Other static constants include VK_ENTER and VK_TAB. This example follows the pattern of all the others: the KeyList object constructed in the KeyFrame constructor is registered as a key event observer within the same constructor.
import java.awt. *;
import java.awt.event. *;
import javax.swing. *;
public class KeyFrame extends JFrame
{
private JTextField tf;
public KeyFrame (String title)
{
super(title);
setSize(300, 300);
tf = new JTextField(20);
getContentPane( ).setLayout(new FlowLayout( ));
getContentPane( ).add(tf);
tf.addKeyListener(new KeyList( ));
// add CloseAndQuit addWindowListener(new CloseAndQuit( ));
}
// inner class
private class KeyList extends KeyAdapter
{
public void keyPressed (KeyEvent k)
{
if (k.getKeyCode( ) == KeyEvent.VK_DELETE)
{
tf.setText("");
}
}
} // end of inner class
} // end of KeyFrame
public class KeyFrameTest
{
public static void main (String [] args)
{
KeyFrame world = new KeyFrame("KeyFrame");
world.setVisible(true);
}
}
Java Assignment Help - Java Homework Help
Struggling with java programming language? Are you not finding solution for your Key listeners homework and assignments? Live Key listeners experts are working for students by solving their doubts & questions during their course studies and training program. We at Expertsmind.com offer Key listeners homework help, java assignment help and Key listeners projects help anytime from anywhere for 24x7 hours. Computer science programming assignments help making life easy for students.
Why Expertsmind for assignment help
- Higher degree holder and experienced experts network
- Punctuality and responsibility of work
- Quality solution with 100% plagiarism free answers
- Time on Delivery
- Privacy of information and details
- Excellence in solving java programming language queries in excels and word format.
- Best tutoring assistance 24x7 hours