import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class TestDialog extends JDialog implements KeyListener
{
public TestDialog()
{
setContentPane(new MyContentPane(this));
}
public static void main(String[] args)
{
TestDialog jd = new TestDialog();
JButton b = new JButton("I do nothing!");
JTextField tf = new JTextField(10);
jd.getContentPane().setLayout(new FlowLayout());
jd.setSize(300, 300);
jd.getContentPane().add(tf);
jd.getContentPane().add(b);
jd.setVisible(true);
jd.addKeyListener(jd);
}
public void keyPressed(KeyEvent e)
{
System.out.println("Key Pressed");
}
public void keyReleased(KeyEvent e)
{
if(e.getKeyCode() == KeyEvent.VK_ESCAPE)
{
System.out.println("We have a winner!!!");
setVisible(false);
}
System.out.println("Key Released");
}
public void keyTyped(KeyEvent e)
{
System.out.println("Key Typed");
}
public class MyContentPane extends JPanel
{
TestDialog dlg;
public MyContentPane(TestDialog dlg)
{
this.dlg = dlg;
}
public Component add(Component comp)
{
comp.addKeyListener(dlg);
return super.add(comp);
}
public Component add(Component comp, int index)
{
comp.addKeyListener(dlg);
return super.add(comp, index);
}
public void add(Component comp, Object constraints)
{
comp.addKeyListener(dlg);
super.add(comp, constraints);
}
public void add(Component comp, Object constraints, int index)
{
comp.addKeyListener(dlg);
super.add(comp, constraints, index);
}
public Component add(String name, Component comp)
{
comp.addKeyListener(dlg);
return super.add(name, comp);
}
}
}
What it is is a modified JDialog which also doubles as a KeyListener.
This allows for me to add a KeyListener to every component that is added to the JDialog. This way the keys can be captured no matter what object has the focus in the dialog. You can use something like this in your program.
-gaev