Java error with WindowAdapter and WindowDestroyer

1k Views Asked by At

I'm just starting out in java and trying to use some example code I found online to get started, but for some reason, I am unable to compile this code. I on Ubuntu 16.04 and I have the "default-jdk" installed.

Here's the code:

import java.awt.*;
import java.awt.event.WindowListener;
import javax.swing.*;
import java.io.*; 


public class Test extends JFrame{
public static void main (String argv []) 
{
    new Test("Window Application");
}

public Test(String title) 
{
    super(title);
    setSize(200, 100);
    addWindowListener((WindowListener) new WindowDestroyer());                 
    setVisible(true);
}

private class WindowDestroyer extends WindowAdapter 
{      
    public void windowClosing(WindowEvent e) 
    {    
        System.exit(0);  
    }                                                             
}

}

When I try doing javac Test.java I get 2 cannot find symbol errors.

private class WindowDestroyer extends WindowAdapter

public void windowClosing(WindowEvent e)

2

There are 2 best solutions below

0
Gino Mempin On

From the Java 8 docs for WindowAdapter, it is defined as java.awt.event.WindowAdapter.

You need to import the class first:

import java.awt.event.WindowAdapter;

in addition to your other imports.

import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowListener;

As a side note, you might be tempted to just do

import java.awt.event.*;

to avoid import errors like that in the future.

I suggest reading the discussions on Why is using a wild card with a Java import statement bad? to have an idea on the pro's and con's of doing so.

4
Oleg Cherednik On

I can see, that you create simple Swing application window and close it close window. You do it in incorrect way. It is much better to use setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE) (only if you not plan to do smth. special before). And use SwingUtilities.invokeLater() to execute asynchronously on the AWT event dispatching thread:

public class Test extends JFrame {

    public static void main(String... ars) {
        SwingUtilities.invokeLater(() -> new Test().setVisible(true));
    }

    public Test() {
        super("Window Application");
        setSize(200, 100);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
     }
}