Monday, August 06, 2007

Focus - lot to do ..

After JDK 1.4, there was a lot to see about focus in Java. Its one of the most interesting and challenging topics in AWT/Swing. JDK1.4 onwards there is one central class which takes care about the focus on components/windows KeyBoardFocusManager. Not only that, now you have freedom to write your own FocusManager.

This is one example where I tried to catch the focus lost and gain event on Focusable components.

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

class ButtonTest{

public static void main(String[] args)
{
ButtonFrame frame = new ButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

class ButtonFrame extends JFrame {
public ButtonFrame()
{
setTitle("Button Test Frame");
setSize(LENGTH,WIDTH);
ButtonPanel panel = new ButtonPanel();
add(panel);
}

int LENGTH = 300;
int WIDTH = 300;

}

class ButtonPanel extends JPanel implements FocusListener {

public ButtonPanel ()
{

JButton button1 = new JButton("Button1");
JButton button2 = new JButton("Button2");
JButton button3 = new JButton("Button3");
JTextField text1 = new JTextField("Enter here");
add(button1);
add(button2);
add(button3);
add(text1);
button1.addFocusListener(this);
button2.addFocusListener(this);
button3.addFocusListener(this);
text1.addFocusListener(this);

}

public void focusGained(FocusEvent e) {
display("Focus gained", e);
}

public void focusLost(FocusEvent e) {
display("Focus lost", e);
}
void display(String prefix, FocusEvent e) {
System.out.println( prefix+" " + e.getComponent().getClass().getName());
}
}

If you are working on AWT or Swing , I would personally prefer to visit this article of JavaWorld:
http://www.javaworld.com/javaworld/jw-07-1998/jw-07-swing-focus.html

1 comment:

Vishnu said...

when a key press event occurs a pop up window
should appear using robot class