Squiz Matrix  4.12.2
 All Data Structures Namespaces Functions Variables Pages
ButtonMenu.java
1 
16 package net.squiz.matrix.ui;
17 
18 import java.awt.*;
19 import java.awt.event.*;
20 import javax.swing.*;
21 import javax.swing.event.*;
22 
23 public class ButtonMenu extends JToggleButton {
24 
25  private JPopupMenu popup;
26  private Icon icon;
27  private Icon depressedIcon;
28  public ButtonMenu(String text, JPopupMenu popup) {
29  super(text);
30  addActionListener(buttonAction);
31  setPopupMenu(popup);
32  }
33 
34  public ButtonMenu(Icon icon) {
35  super(icon);
36  addActionListener(buttonAction);
37  }
38 
39  public ButtonMenu(Icon icon, Icon depressedIcon) {
40  super(icon);
41  this.icon = icon;
42  this.depressedIcon = depressedIcon;
43  addActionListener(buttonAction);
44  }
45 
46  public void setPopupMenu(JPopupMenu newPopup) {
47  if (popup != null) {
48  popup.removePopupMenuListener(popupListener);
49  }
50  popup = newPopup;
51  if (popup != null) {
52  popup.addPopupMenuListener(popupListener);
53  }
54  }
55 
56  protected void showPopup() {
57  if (popup != null) {
58  popup.show(ButtonMenu.this, 0, getSize().height);
59  }
60  }
61 
62  protected void hidePopup() {
63  if (popup != null) {
64  popup.setVisible(false);
65  }
66  }
67 
68  private ActionListener buttonAction = new ActionListener() {
69  public void actionPerformed(ActionEvent event) {
70  if (isSelected()) {
71  showPopup();
72  if (depressedIcon != null)
73  setIcon(depressedIcon);
74  } else {
75  hidePopup();
76  if (depressedIcon != null)
77  setIcon(icon);
78  }
79  }
80  };
81 
82  private PopupMenuListener popupListener = new PopupMenuListener() {
83  public void popupMenuWillBecomeInvisible(PopupMenuEvent event) {
84  if (icon != null)
85  setIcon(icon);
86  SwingUtilities.invokeLater(new Runnable() {
87  public void run() {
88  doClick();
89  }
90  });
91  }
92 
93  public void popupMenuWillBecomeVisible(PopupMenuEvent event) {}
94  public void popupMenuCanceled(PopupMenuEvent event) {}
95  };
96 }