0

I want have a very easy effect: create a window, then if I press a button, it will be closed.

So I write the following code, but it doesn't work.

import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class test
{
    public static void main(String[] args) 
    {
        final Window wnd = new Window(new Frame());
        wnd.setLocation(100, 100);
        wnd.setSize(400,300);
        wnd.setVisible(true);
        wnd.requestFocusInWindow();


        wnd.addKeyListener(
          new KeyAdapter() {
            public void keyPressed(KeyEvent event)
            {
              wnd.setVisible(false);
              wnd.dispose();
              System.exit(0);
            }
          }
        );
   }
}

I guess the problem may be lie in:

wnd.requestFocusInWindow();

because the returned value of wnd.requestFocusInWindow() is always "false". Why? How can I fix the problem? (I use ubuntu and Eclipse.)

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
xirururu
  • 5,028
  • 9
  • 35
  • 64
  • 2
    1) Why use AWT components rather than Swing? See [this answer](http://stackoverflow.com/a/6255978/418556) for many good reasons to abandon AWT. 2) `wnd.setFocusable(true);` – Andrew Thompson Aug 15 '14 at 14:40
  • Thanks Andrew, the answer link is really useful! I learn the GUI programming just at beginning, may be I can now skip the chapter about "awt" and direct go to "swing". – xirururu Aug 15 '14 at 21:35
  • *"skip the chapter about "awt" and direct go to "swing""* Yes! – Andrew Thompson Aug 16 '14 at 02:44

0 Answers0