Wednesday, May 4, 2011

Popup Button


A PopupButton Component written by
Pat Paternostro
JDJ 5-10 p82

Listing 1
import java.awt.*;
import java.awt.event.*;

public abstract class PopupButton extends Button implements ActionListener
{
 private PopupMenu popup;

 protected PopupButton(String[] items, Container parent)
 {
  this("",items,parent);
 }

 protected PopupButton(String label, String[] items, Container parent)
 {
  super(label + " Û ");

  popup = new PopupMenu();

  MenuItem menuItems[] = new MenuItem[items.length];

  for(int i = 0; i < items.length; i++)
  {
   menuItems[i] = new MenuItem(items[i]);
   menuItems[i].addActionListener(this);
   popup.add(menuItems[i]);
  }

  parent.add(popup);

  addActionListener(new ActionListener() {
   public void actionPerformed(ActionEvent evt) {
    popup.show(PopupButton.this,0,PopupButton.this.getSize().height);}});
 }
}

Listing 2
import java.awt.event.*;
import java.awt.*;

public class PopupButtonTest {
 public static void main(String args[]) {
  new PopupButtonTestFrame();
 }
}

class PopupButtonTestFrame extends Frame {
 Panel panel = new Panel();
 MyPopupButton mpb1 = new MyPopupButton("Colors",new String[]{"Red","Green","Blue"},this);
 MyPopupButton mpb2 = new MyPopupButton("Fruit",new String[]{"Apples","-","Oranges","-","Bannanas"},this);

 PopupButtonTestFrame() {
  super();

  /* Add the window listener */
  addWindowListener(new WindowAdapter() {
   public void windowClosing(WindowEvent evt) {
    dispose(); System.exit(0);}});

  /* Size the frame */
  setSize(200,200);

  /* Center the frame */
  Dimension screenDim = Toolkit.getDefaultToolkit().getScreenSize();
  Rectangle frameDim = getBounds();
  setLocation((screenDim.width - frameDim.width) / 2,(screenDim.height - frameDim.height) / 2);

  panel.add(mpb1);
  panel.add(mpb2);
  add(BorderLayout.NORTH,panel);

  /* Show the frame */
  setVisible(true);
 }
}

class MyPopupButton extends PopupButton
{
 public MyPopupButton(String label, String[] items, Container parent)
 {
  super(label,items,parent);
 }

 public void actionPerformed(ActionEvent evt)
 {
  String command = evt.getActionCommand();  System.out.println("You selected the " + command + "
 popup menu item!");
 }
 }

No comments:

Post a Comment