How to add KeyListener to JDialog

امیرحسین لطیفی - ۱۲ دی ۱۳۸۶

You can add KeyListener to your JDialog component as you can add it to any other swing components but when you add other components to JDialog, they eat key events.
To solve this problem you should register KeyboardAction for JDialog. In below code snippet typically I want sense F1 key pressing to do something:

ActionListener actionListener = new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
};
KeyStroke keyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_F1, 0);
JRootPane rootPane = getRootPane();
rootPane.registerKeyboardAction(actionListener, keyStroke,JComponent.WHEN_IN_FOCUSED_WINDOW);


Force Swing componets to repaint

امیرحسین لطیفی - ۳ دی ۱۳۸۶

If n times repaint() method callings don’t refresh your your frame, use this one to force your Swing components to repaint!

Graphics g = getGraphics();
if (g != null) paintComponents(g);
else repaint();

Related thread on sun forum :
http://forum.java.sun.com/thread.jspa?threadID=497595