awt window not closing when close button is clicked
Asked Answered
S

3

6

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);
            }
        } );
    }
}
Serriform answered 5/10, 2012 at 11:6 Comment(1)
AWT is heavyweight i.e. its components uses the resources of system, Swing provides platform-independent and lightweight components such as JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.Mineral
E
5

You code is incorrect. Instead of

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

try

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

This will close your window.

Edgardo answered 5/10, 2012 at 11:13 Comment(0)
M
4

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.

Mineral answered 4/3, 2016 at 8:44 Comment(0)
R
-1

Check this:

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

It tells basically the windows manager to shutdown your app when "X" is pressed.

Rocca answered 5/10, 2012 at 11:10 Comment(2)
dude Gambler using AWT component not the Swing component. this method is not available setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); for Frame this is for JFrameIzak
Seriously? -1. This answer just shows that you didn't read the question. It uses AWT, not Swing. I would expect a little more as well.Embroideress

© 2022 - 2024 — McMap. All rights reserved.