GUI: JTextField, JLabel and JButton

A typical applet requires the input of information to be processed, and the output of results. This example does just that, using two text fields and a button.


// Applet with input and output fields
// AppletwithFields
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class AppletwithFields extends JApplet implements ActionListener{

   JLabel lblInput, lblOutput;
   JTextField txtInput, txtOutput;
   JButton btnExec;

   public void init(){

      // Get pane from applet
      Container c=getContentPane();
      // specify FlowLayout for Pane
      c.setLayout(new FlowLayout());

      // GUI details
      // Label and field for input
      lblInput=new JLabel("Input Number");
      c.add(lblInput);
      txtInput=new JTextField(25);
      txtInput.setEditable(true);
      c.add(txtInput);
      // Label and field for output
      lblOutput=new JLabel("Square-Root");
      c.add(lblOutput);
      txtOutput=new JTextField(25);
      txtOutput.setEditable(false);
      c.add(txtOutput);
      // button for Execute
      btnExec=new JButton("Calculate");
      btnExec.addActionListener(this);
      c.add(btnExec);
  }

  public void actionPerformed(ActionEvent actionEvent){
     double dNum=Double.parseDouble(txtInput.getText());
     String output="";
     output += Math.sqrt(dNum);
     txtOutput.setText(output);
     showStatus("Square-root extraction completed");
  }
}