Using JRadioButtons in Applets

This is adapted version of the preceding applet with a group of JRadioButtons instead of four individual buttons. We added the buttons to a ButtonGroup and to a JPanel and set the button selected initially with setSelected. The next page shows selection of items with a JComboBox

The code follows this screenshot of the applet in action.

JRadioButton applet (400 x 270) in action

JRadioButton applet (400 x 270) in action

namespace jradiobutton_demo;

interface

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

type
  JRadioButtonDemo = public class(Applet, ActionListener)
  private
    rbtnAppend, rbtnReplace, rbtnInsert, rbtnCopy : JRadioButton;
    txtNew : TextField;
    taEdit, taCopy : JTextArea;
    initText : String := 'This is the starting text to modify by pressing the buttons.';
    lblInstruction : Label;
    radioPanel : JPanel;
    rgroup : ButtonGroup;
   
  public
    method init; override;
    method actionPerformed(e : ActionEvent);
  end;

implementation

method JRadioButtonDemo.init;
begin
  Background := Color.green.darker;
  lblInstruction := new Label('Enter the text to append, insert, or replace with.');
  add(lblInstruction); 
  txtNew := new TextField('', 40);
  add(txtNew);
  radioPanel := new JPanel(new GridLayout(0, 1));
  rgroup := new ButtonGroup;
  rbtnAppend := new JRadioButton('Append');
  rbtnReplace := new JRadioButton('Replace selected text');
  rbtnInsert := new JRadioButton('Insert at cursor position');
  rbtnCopy := new JRadioButton('Copy to lower TextArea');
  rgroup.add(rbtnAppend);
  rgroup.add(rbtnReplace);
  rgroup.add(rbtnInsert);
  rgroup.add(rbtnCopy);
  radioPanel.add(rbtnAppend);
  radioPanel.add(rbtnReplace);
  radioPanel.add(rbtnInsert);
  radioPanel.add(rbtnCopy);

  rbtnAppend.addActionListener(self);
  rbtnReplace.addActionListener(self);
  rbtnInsert.addActionListener(self);
  rbtnCopy.addActionListener(self);
  rbtnAppend.setselected(true);

  taEdit := new JTextArea(initText, 5, 20); 
  taCopy := new JTextArea('', 5, 20);
  taEdit.setLineWrap(true);
  taCopy.setLineWrap(true);
  taEdit.setWrapStyleWord(true);
  taCopy.setWrapStyleWord(true);
  add(taEdit);
  add(radioPanel);
  add(taCopy);
  taEdit.setForeground (Color.blue.brighter);
  taCopy.setForeground (Color.red);
end;

method JRadioButtonDemo.actionPerformed(e : ActionEvent);
begin
  if e.getSource = rbtnAppend then
    taEdit.append(txtNew.getText);
 
  if e.getSource = rbtnReplace then
    taEdit.replaceRange(txtNew.getText,  taEdit.getSelectionStart, taEdit.getSelectionEnd); 

  if e.getSource = rbtnInsert then 
    taEdit.insert(txtNew.getText, taEdit.getCaretPosition); 

  if e.getSource = rbtnCopy then 
    taCopy.setText(taEdit.getText);  
end;

end.


Programming - a skill for life!

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