Choice Removal Demo

Web Configuration:


<applet code="ChoiceRemove.class" codebase="applet" width=300 height=150>
</applet>

Source Code:


/* ChoiceRemove.java
*
* This example creates a choice and a row of buttons that
* control the insertion and removal of items from the
* choice.
*/

import java.awt.*;
import java.awt.event.*;


public class ChoiceRemove extends java.applet.Applet implements ActionListener{
    Choice choice = new Choice();
    Button removeBtn = new Button ("Remove");
    Button removeAllBtn = new Button ("Remove All");
    Button insertBtn = new Button ("Insert");
    int lastItemCount = 0;

    public void init () {
        //Initialize the choice with ten items
        for (int i = 0; i <10; i++){
            choice.addItem("Item" + (lastItemCount++));
        }

        // Listen for events.
        removeBtn.addActionListener(this);
        removeAllBtn.addActionListener(this);
        insertBtn.addActionListener(this);

        Panel p = new Panel(new GridLayout(1,0));
        p.add(removeBtn);
        p.add(removeAllBtn);
        p.add(insertBtn);

        setLayout( new BorderLayout());
        add(p, BorderLayout.NORTH);
        add(choice, BorderLayout.CENTER);
    }

    public void actionPerformed(ActionEvent e) {
        String cmd = e.getActionCommand();
        if (cmd.equals("Remove All")){
            choice.removeAll();
        } else {
            int target = choice.getSelectedIndex();
            if (cmd.equals("Remove")){
                if (target >= 0){
                     choice.remove(target);
                }
            } else {
                if (target >= 0){
                     choice.insert("item" +
                             (lastItemCount++),target);
                     choice.select(target);
                } else {
                     choice.add("Item" +(lastItemCount++));
                }
            }
        }
        removeBtn.setEnabled(choice.getItemCount() > 0);
        removeAllBtn.setEnabled(choice.getItemCount() >0);
    }
}

Copyright©2002, All Right Reserved

Department of Geography, San Diego State University