Add window listener to a JFrame in Java

Description

The following code shows how to add window listener to a JFrame.

Example


import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
/*from   ww  w. j ava 2s  . c o  m*/
import javax.swing.JFrame;

public class Main extends JFrame {
  public Main() {
    setSize(400, 300);

    WindowListener wndCloser = new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        System.exit(0);
      }
    };
    addWindowListener(wndCloser);
    setVisible(true);
  }

  public static void main(String args[]) {
    new Main();
  }
}

The code above generates the following result.

Add window listener to a JFrame in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer