Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awt window not closing when close button is clicked

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);
            }
        } );
    }
}
like image 928
Gambler Avatar asked Oct 05 '12 11:10

Gambler


2 Answers

You code is incorrect. Instead of

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

try

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

This will close your window.

like image 55
Peter Ilfrich Avatar answered Sep 22 '22 12:09

Peter Ilfrich


It's better to use the method public void dispose()

vk.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent we) {
            vk.dispose(); // use dispose method 
         }
     }
);

AWT is heavyweight i.e. its components uses the resources of system.

Windows are non-blocking. Meaning that once you create one in code, your code continues to execute.

This means that your Window probably goes out of scope immediately after creation, unless you explicitly stored a reference to it somewhere else. The Window is still on screen at this point.

This also means you need some other way to get rid of it when you're done with it. Enter the Window dispose() method, which can be called from within one of the Window's listeners.

like image 43
Jaimin Patel Avatar answered Sep 18 '22 12:09

Jaimin Patel