Java ActionEvent check event source

Description

Java ActionEvent check event source

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

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

public class Main extends JFrame {
  private JButton buttonOK = new JButton("OK");
  private JTextField textName = new JTextField(15);

  public Main() {
    setSize(325, 100);//from   w w  w . j a  v a2 s  .  co m
    setTitle("Who Are You?");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    ButtonListener bl = new ButtonListener();
    JPanel panel1 = new JPanel();
    panel1.add(new JLabel("Enter your name: "));
    panel1.add(textName);
    panel1.add(buttonOK);
    
    buttonOK.addActionListener(bl);

    add(panel1);
    pack();
    setVisible(true);
  }

  private class ButtonListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      if (e.getSource() == buttonOK) {
        String name = textName.getText();
        if (name.length() == 0) {
          JOptionPane.showMessageDialog(Main.this, "You didn't enter anything!", "Moron",
              JOptionPane.INFORMATION_MESSAGE);
        } else {
          JOptionPane.showMessageDialog(Main.this, "Good morning " + textName.getText(), "Salutations",
              JOptionPane.INFORMATION_MESSAGE);
        }
        textName.requestFocus();
      }
    }
  }
  public static void main(String[] args) {
    new Main();
  }
}



PreviousNext

Related