Using the Event-Dispatching Thread to Build a GUI in an Applet - Java Applet

Java examples for Applet:Applet Creation

Description

Using the Event-Dispatching Thread to Build a GUI in an Applet

Demo Code

import javax.swing.JApplet;
import javax.swing.SwingUtilities;
import java.awt.Container;
import java.awt.FlowLayout;
import java.lang.reflect.InvocationTargetException;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import static javax.swing.JOptionPane.INFORMATION_MESSAGE;
import static javax.swing.JOptionPane.ERROR_MESSAGE;

public class Main extends JApplet {
  @Override/*from  www . j  a v  a2 s .  c  om*/
  public void init() {
    try {
      SwingUtilities.invokeAndWait(() -> initApplet());
    } catch (InterruptedException | InvocationTargetException e) {
      JOptionPane.showMessageDialog(null, e.getMessage(), "Error",
          ERROR_MESSAGE);
    }
  }

  private void initApplet() {
    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