awt window not closing when close button is clicked

Gambler picture Gambler · Oct 5, 2012 · Viewed 9.7k times · Source

I implemented a sample class for a Virtual KeyBoard and ran this VirtualKeyboardTest.The keyboard appears but the main problem is that it is not closing properly when the x button is clicked.How can i rectify this?

import java.awt.*;
import java.awt.event.*;

public class VirtualKeyboardTest
{
    public static void main(String args[])
    {
        VirtualKeyboard vk = new VirtualKeyboard();
        vk.setSize(500,300);
        vk.setVisible(true);
        Frame f1 = new Frame();
        f1.addWindowListener( new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent we) {

                System.exit(0);
            }
        } );
    }
}

Answer

Peter Ilfrich picture Peter Ilfrich · Oct 5, 2012

You code is incorrect. Instead of

f1.addWindowListener( new WindowAdapter() {
  ...

try

vk.addWindowListener( new WindowAdapter() {
  ...

This will close your window.