Saying Good Morning With A Text Field - Java Swing

Java examples for Swing:JTextField

Description

Saying Good Morning With A Text Field

Demo Code

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 {
  public static void main(String[] args) {
    new Main();//from   w  ww .  j  a  v  a  2 s.  c  o  m
  }

  private JButton buttonOK;
  private JTextField textName;

  public Main() {
    this.setSize(325, 100);
    this.setTitle("Who Are You?");
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    ButtonListener bl = new ButtonListener();

    JPanel panel1 = new JPanel();

    panel1.add(new JLabel("Enter your name: "));

    textName = new JTextField(15);
    panel1.add(textName);

    buttonOK = new JButton("OK");
    buttonOK.addActionListener(bl);
    panel1.add(buttonOK);

    this.add(panel1);

    this.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();
      }
    }
  }
}

Related Tutorials