Add Button Demo

 

Web Configuration:

<applet code="AddButton.class" codebase="applet" width=200 height=150>
</applet>
 

Source Code

/*

* AddButton.java

* This example creates a list of random numbers in a list.
* Pressing the Add button adds more random numbers. Pressing
* Remove removes the selected number from the list. Pressing
* Shift-Remove removes all the numbers from the list.
*/

import java.awt.*;

import java.awt.event.*;

public class AddButton extends java.applet.Applet implements ActionListener{
   
    Button addButton = new Button ("ADD");
    Button removeButton = new Button ("REMOVE");
    Label removeAll = new Label ("Press Shift+Remove to Remove All", Label.LEFT);
    List list = new List();

    public void init () {
        addItems();
       
        //Listen for events
        addButton.addActionListener(this);
        removeButton.addActionListener(this);

        //Layout Components
        Panel p = new Panel(new GridLayout(0,1));
        p.add(removeButton);
        p.add(removeAll);
        setLayout(new BorderLayout());
        add(addButton, BorderLayout.NORTH);
        add(p, BorderLayout.SOUTH);
        add(list, BorderLayout.CENTER);
     }

    public void actionPerformed(ActionEvent e) {
        if ("ADD".equals(e.getActionCommand())){
            addItems();
        } else {
            // if the shift key is enabled, remove all the items.
            System.out.println(e.getModifiers());
            if ((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0) {
                list.removeAll();
            } else if (list.getSelectedIndex() >= 0){
                list.remove(list.getSelectedIndex());
            }
        }
    }

    // Generate some random items
    void addItems(){
        for (int i=0; i<5; i++){
            list.addItem(" " +Math.random());
        }
    }
}

Copyright©2002, All Right Reserved

Department of Geography, San Diego State University