A HelloApplet Applet That Displays a Message Using a JLabel - Java Applet

Java examples for Applet:Applet Creation

Description

A HelloApplet Applet That Displays a Message Using a JLabel

Demo Code

import static javax.swing.JOptionPane.INFORMATION_MESSAGE;

import java.awt.Container;
import java.awt.FlowLayout;

import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

public class Main extends JApplet {
  @Override/*  ww w  . ja v  a2  s  . com*/
  public void init() {
    JLabel nameLabel = new JLabel("Your Name:");
    JTextField nameFld = new JTextField(15);
    JButton sayHelloBtn = new JButton("Say Hello");

    sayHelloBtn.addActionListener(e -> sayHello(nameFld.getText()));

    Container contentPane = this.getContentPane();
    contentPane.setLayout(new FlowLayout());
    contentPane.add(nameLabel);
    contentPane.add(nameFld);
    contentPane.add(sayHelloBtn);
  }

  private void sayHello(String name) {
    String msg = "Hello there";
    if (name.length() > 0) {
      msg = "Hello " + name;
    }
    JOptionPane.showMessageDialog(null, msg, "Hello", INFORMATION_MESSAGE);
  }
}

Related Tutorials