Friday, January 18, 2008

Java Coding Question And Answers

Handling Events with an Anonymous Class

If an event handler is specific to a component (that is, not shared by other components), there is no need to declare a class to handle the event. The event handler can be implemented using an anonymous inner class. This example demonstrates an anonymous inner class to handle key events for a component.

component.addKeyListener(new KeyAdapter() {public void keyPressed(KeyEvent evt) { }});

Handling Action Events

Action events are fired by subclasses of AbstractButton and includes buttons, checkboxes, and menus.
AbstractButton button = new JButton(“OK");
button.addActionListener(new MyActionListener());
public class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent evt) {
// Determine which abstract
// button fired the event.
AbstractButton button = (AbstractButton)evt.getSource();
}
}
Handling Key Presses

You can get the key that was pressed either as a key character (which is a Unicode character) or as a key code (a special value representing a particular key on the keyboard).

component.addKeyListener(new MyKeyListener());
public class MyKeyListener extends KeyAdapter {
public void keyPressed(KeyEvent evt) {
// Check for key characters.
if (evt.getKeyChar() == 'a') {
process(evt.getKeyChar());
}
// Check for key codes.
if (evt.getKeyCode() == KeyEvent.VK_HOME) {
process(evt.getKeyCode());
}
}
}

Handling Mouse Clicks

component.addMouseListener(new MyMouseListener());
public class MyMouseListener extends MouseAdapter {
public void mouseClicked(MouseEvent evt) {
if ((evt.getModifiers() &
InputEvent.BUTTON1_MASK) != 0) {
processLeft(evt.getPoint());
}
if ((evt.getModifiers() &
InputEvent.BUTTON2_MASK) != 0) {
processMiddle(evt.getPoint());
}
if ((evt.getModifiers() &
InputEvent.BUTTON3_MASK) != 0) {
processRight(evt.getPoint());
}
}
}

Handling Mouse Motion

component.addMouseMotionListener(new MyMouseMotionListener());
public class MyMouseMotionListener extends MouseMotionAdapter {
public void mouseMoved(MouseEvent evt) {
// Process current position of cursor
// while all mouse buttons are up.
process(evt.getPoint());
}
public void mouseDragged(MouseEvent evt) {
// Process current position of cursor
// while mouse button is pressed.
process(evt.getPoint());
}
}

No comments:

 
Google