Clickme Application With An Exit Button - Java Swing

Java examples for Swing:JButton

Description

Clickme Application With An Exit Button

Demo Code

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class Main extends JFrame {
  public static void main(String[] args) {
    new Main();//from  ww w. j  a v a 2s. c  o m
  }

  private JButton button1, exitButton;

  public Main() {
    this.setSize(275, 100);
    this.setTitle("I'm Listening");
    this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);

    ClickListener cl = new ClickListener();

    JPanel panel1 = new JPanel();

    addWindowListener(new WindowAdapter() {
      public void windowClosing(WindowEvent e) {
        exitButton.doClick();
      }
    });

    button1 = new JButton("Click Me!");
    button1.addActionListener(cl);
    panel1.add(button1);

    exitButton = new JButton("Exit");
    exitButton.addActionListener(cl);
    panel1.add(exitButton);

    this.add(panel1);

    this.setVisible(true);
  }

  private class ClickListener implements ActionListener {
    private int clickCount = 0;

    public void actionPerformed(ActionEvent e) {
      if (e.getSource() == button1) {
        clickCount++;
        if (clickCount == 1)
          button1.setText("I've been clicked!");
        else
          button1.setText("I've been clicked " + clickCount + " times!");
      } else if (e.getSource() == exitButton) {
        if (clickCount > 0)
          System.exit(0);
        else {
          JOptionPane.showMessageDialog(Main.this, "You must click at least once!", "Not so fast, buddy",
              JOptionPane.ERROR_MESSAGE);
        }
      }
    }
  }
}

Related Tutorials