Google Tag Manager

2014/09/29

aterai

Change a layout of a JPopupMenu to use their iconic menu items

Code

JPopupMenu popup = new JPopupMenu();
GridBagConstraints c = new GridBagConstraints();
popup.setLayout(new GridBagLayout());
c.gridheight = 1;

c.weightx = 1.0;
c.weighty = 0.0;
c.fill = GridBagConstraints.HORIZONTAL;
c.anchor = GridBagConstraints.CENTER;

c.gridwidth = 1;
c.gridy = 0;
c.gridx = 0; popup.add(makeButton("\u21E6"), c);
c.gridx = 1; popup.add(makeButton("\u21E8"), c);
c.gridx = 2; popup.add(makeButton("\u21BB"), c);
c.gridx = 3; popup.add(makeButton("\u2729"), c);

c.gridwidth = 4;
c.gridx = 0;
c.insets = new Insets(2, 0, 2, 0);
c.gridy = 1; popup.add(new JSeparator(), c);
c.insets = new Insets(0, 0, 0, 0);
c.gridy = 2; popup.add(new JMenuItem("aaaaaaaaaa"), c);
c.gridy = 3; popup.add(new JPopupMenu.Separator(), c);
c.gridy = 4; popup.add(new JMenuItem("bbbb"), c);
c.gridy = 5; popup.add(new JMenuItem("ccccccccccccccccccccc"), c);
c.gridy = 6; popup.add(new JMenuItem("dddddddddd"), c);
final Icon icon = new SymbolIcon(symbol);
JMenuItem b = new JMenuItem() {
  private final Dimension d = new Dimension(icon.getIconWidth(), icon.getIconHeight());
  @Override public Dimension getPreferredSize() {
    return d;
  }
  @Override public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Dimension cd = getSize();
    Dimension pd = getPreferredSize();
    int offx = (int) (.5 + .5 * (cd.width  - pd.width));
    int offy = (int) (.5 + .5 * (cd.height - pd.height));
    icon.paintIcon(this, g, offx, offy);
  }
};
b.setOpaque(true);

References

No comments:

Post a Comment