Using Buttons and TextFields in Applets

This demonstrates the use of a Button, Label and TextField. You need an action listener for the button-press event and for the enter-text event of the TextField.

If you need a button with an image, use a JButton (and add javax.swing to the uses clause).

The code follows this screenshot of the applet in action.

Button applet (200 x 70) in action

Button applet (200 x 70) in action

namespace button_demo;

interface

uses
  java.util, java.applet.*, java.awt.*;

type
  ButtonDemo = public class(Applet, ActionListener)
  private
    count : Integer := 0;
    btn : Button;
    lbl : Label;
    txt : TextField;
  public
    method init; override;
    method actionPerformed(e : ActionEvent);
  end;

implementation

method ButtonDemo.init;
begin
  Background := Color.yellow.darker;
  btn := new Button('Press me if you dare!');
  add(btn);
  btn.addActionListener(self);
  txt := new TextField('', 15);
  add(txt);
  txt.addActionListener(self);
  lbl := new Label('Please enter name first.           ');
  lbl.setForeground (Color.blue.brighter);
  add(lbl);
end;

method ButtonDemo.actionPerformed(e : ActionEvent);
begin
  if e.getSource = btn then 
    begin
      inc(count);
      lbl.setText('Press number ' + count.toString + ' by ' + txt.getText);
    end;

  if e.getSource = txt then 
    lbl.setText('Hello ' + txt.getText + '!');
end;

end.

Programming - a skill for life!

How to use widgets such as JButtons, JTextAreas, JComboBoxes and dialogues in Oxygene for Java applets