Passing Parameters to Applets - Java Applet

Java examples for Applet:Applet Creation

Introduction

Passing Parameters to an Applet Using the <param> Tag

<applet code="Main" width="100" height="100">
        <param name="buttonHeight" value="20" />
        <param name="buttonText" value="Hello" />
</applet>
import java.awt.Container;
import java.awt.FlowLayout;

import javax.swing.JApplet;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class Main extends JApplet {
  private JTextArea welcomeTextArea = new JTextArea(2, 20);
  private JButton helloButton = new JButton();

  @Override
  public void init() {
    Container contentPane = this.getContentPane();
    contentPane.setLayout(new FlowLayout());

    contentPane.add(new JScrollPane(welcomeTextArea));
    contentPane.add(helloButton);

    helloButton.addActionListener(e -> showParameters());
    welcomeTextArea.setEditable(false);
    String welcomeMsg = this.getParameter("welcomeText");
    if (welcomeMsg == null || welcomeMsg.equals("")) {
      welcomeMsg = "Welcome!";
    }
    welcomeTextArea.setText(welcomeMsg);

    String helloButtonText = this.getParameter("helloButtonText");
    if (helloButtonText == null || helloButtonText.equals("")) {
      helloButtonText = "Hello";
    }

    helloButton.setText(helloButtonText);
  }

  private void showParameters() {
    String welcomeText = this.getParameter("welcomeText");
    String helloButtonText = this.getParameter("helloButtonText");

    String msg = "welcomeText=" + welcomeText + "\nhelloButtonText=" + helloButtonText;
    JOptionPane.showMessageDialog(null, msg);
  }
}

Related Tutorials