Google Tag Manager

Showing posts with label JToolBar. Show all posts
Showing posts with label JToolBar. Show all posts

2024/03/31

Switching between JToolBar and JMenuBar

Click on the hamburger menu-like JButton placed on the JToolBar to switch this with the JMenuBar

Code

JMenuBar mainMenuBar = makeMenuBar();
JButton button = makeHamburgerMenuButton(mainMenuBar);
JMenuBar wrappingMenuBar = new JMenuBar();
wrappingMenuBar.add(makeToolBar(button));
EventQueue.invokeLater(() -> getRootPane().setJMenuBar(wrappingMenuBar));

PopupMenuListener handler = new PopupMenuListener() {
  @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
    // not need
  }

  @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
    EventQueue.invokeLater(() -> {
      if (MenuSelectionManager.defaultManager().getSelectedPath().length == 0) {
        getRootPane().setJMenuBar(wrappingMenuBar);
      }
    });
  }

  @Override public void popupMenuCanceled(PopupMenuEvent e) {
    EventQueue.invokeLater(() -> getRootPane().setJMenuBar(wrappingMenuBar));
  }
};
for (int i = 0; i < mainMenuBar.getMenuCount(); i++) {
  mainMenuBar.getMenu(i).getPopupMenu().addPopupMenuListener(handler);
}
// ...
private JButton makeHamburgerMenuButton(JMenuBar menuBar) {
  JButton button = new JButton("Ξ") {
    @Override public Dimension getPreferredSize() {
      Dimension d = super.getPreferredSize();
      d.height = menuBar.getMenu(0).getPreferredSize().height;
      return d;
    }

    @Override public void updateUI() {
      super.updateUI();
      setContentAreaFilled(false);
      setFocusPainted(false);
      setBorder(BorderFactory.createEmptyBorder(0, 2, 0, 2));
    }
  };
  button.addActionListener(e -> {
    getRootPane().setJMenuBar(menuBar);
    getRootPane().revalidate();
    EventQueue.invokeLater(() -> menuBar.getMenu(0).doClick());
  });
  button.setMnemonic('\\');
  button.setToolTipText("Main Menu(Alt+\\)");
  return button;
}

References

2023/09/30

Move the selected item in JList up or down by clicking on the JButton placed on the JToolBar

Since DefaultListModel does not have a move method like DefaultTableModel#moveRow(int start, int end, int to), the DefaultListModel#get(int index), DefaultListModel#remove(int index), and DefaultListModel#add(int index, E element) methods are used in combination to move selected items up and down the JList.

Code

JButton up = new JButton("▲");
up.setFocusable(false);
up.addActionListener(e -> {
  int[] pos = list.getSelectedIndices();
  if (pos.length == 0) {
    return;
  }
  boolean isShiftDown = (e.getModifiers() & ActionEvent.SHIFT_MASK) != 0;
  int index0 = isShiftDown ? 0 : Math.max(0, pos[0] - 1);
  int idx = index0;
  for (int i : pos) {
    model.add(idx, model.remove(i));
    list.addSelectionInterval(idx, idx);
    idx++;
  }
  // scroll
  Rectangle r = list.getCellBounds(index0, index0 + pos.length);
  list.scrollRectToVisible(r);
});

JButton down = new JButton("▼");
down.setFocusable(false);
down.addActionListener(e -> {
  int[] pos = list.getSelectedIndices();
  if (pos.length == 0) {
    return;
  }
  boolean isShiftDown = (e.getModifiers() & ActionEvent.SHIFT_MASK) != 0;
  int max = model.getSize();
  int index = isShiftDown ? max : Math.min(max, pos[pos.length - 1] + 1);
  int index0 = index;
  // copy
  for (int i : pos) {
    int idx = Math.min(model.getSize(), ++index);
    model.add(idx, model.get(i));
    list.addSelectionInterval(idx, idx);
  }
  // clean
  for (int i = pos.length - 1; i >= 0; i--) {
    model.remove(pos[i]);
  }
  // scroll
  Rectangle r = list.getCellBounds(index0 - pos.length, index0);
  list.scrollRectToVisible(r);
});

References

2014/03/27

Long pressing the JButton to get a JPopupMenu

Code

class PressAndHoldHandler extends AbstractAction implements MouseListener {
  public final JPopupMenu pop = new JPopupMenu();
  public final ButtonGroup bg = new ButtonGroup();
  private AbstractButton arrowButton;
  private final Timer holdTimer = new Timer(1000, e -> {
    if (arrowButton != null && arrowButton.getModel().isPressed()
        && holdTimer.isRunning()) {
      holdTimer.stop();
      pop.show(arrowButton, 0, arrowButton.getHeight());
      pop.requestFocusInWindow();
    }
  });

  public PressAndHoldHandler() {
    super();
    holdTimer.setInitialDelay(1000);
    pop.setLayout(new GridLayout(0, 3, 5, 5));
    for (MenuContext m: makeMenuList()) {
      AbstractButton b = new JRadioButton(m.command);
      b.setActionCommand(m.command);
      b.setForeground(m.color);
      b.setBorder(BorderFactory.createEmptyBorder());
      b.addActionListener(e -> {
        System.out.println(e.getActionCommand());
        pop.setVisible(false);
      });
      pop.add(b);
      bg.add(b);
    }
  }

  private List<MenuContext> makeMenuList() {
    return Arrays.asList(
      new MenuContext("BLACK", Color.BLACK),
      new MenuContext("BLUE", Color.BLUE),
      new MenuContext("CYAN", Color.CYAN),
      new MenuContext("GREEN", Color.GREEN),
      new MenuContext("MAGENTA", Color.MAGENTA),
      new MenuContext("ORANGE", Color.ORANGE),
      new MenuContext("PINK", Color.PINK),
      new MenuContext("RED", Color.RED),
      new MenuContext("YELLOW", Color.YELLOW));
  }

  @Override public void actionPerformed(ActionEvent e) {
    System.out.println("actionPerformed");
    if (holdTimer.isRunning()) {
      ButtonModel model = bg.getSelection();
      if (model != null) {
        System.out.println(model.getActionCommand());
      }
      holdTimer.stop();
    }
  }

  @Override public void mousePressed(MouseEvent e) {
    System.out.println("mousePressed");
    Component c = e.getComponent();
    if (SwingUtilities.isLeftMouseButton(e) && c.isEnabled()) {
      arrowButton = (AbstractButton) c;
      holdTimer.start();
    }
  }

  @Override public void mouseReleased(MouseEvent e) {
    holdTimer.stop();
  }

  @Override public void mouseExited(MouseEvent e) {
    if (holdTimer.isRunning()) {
      holdTimer.stop();
    }
  }

  @Override public void mouseEntered(MouseEvent e) {
    /* not needed */
  }

  @Override public void mouseClicked(MouseEvent e) {
    /* not needed */
  }
}

References

2013/04/25

Rearrange JToolBar icon by drag and drop

Code

class DragHandler extends MouseAdapter {
  private final JWindow window = new JWindow();
  private Component draggingComponent = null;
  private int index = -1;
  private Component gap = Box.createHorizontalStrut(24);
  private Point startPt = null;
  private int gestureMotionThreshold = DragSource.getDragThreshold();
  public DragHandler() {
    window.setBackground(new Color(0x0, true));
  }

  @Override public void mousePressed(MouseEvent e) {
    JComponent parent = (JComponent) e.getComponent();
    if (parent.getComponentCount() <= 1) {
      startPt = null;
      return;
    }
    startPt = e.getPoint();
  }

  @Override public void mouseDragged(MouseEvent e) {
    Point pt = e.getPoint();
    JComponent parent = (JComponent) e.getComponent();
    if (startPt != null && startPt.distance(pt) > gestureMotionThreshold) {
      startPt = null;
      Component c = parent.getComponentAt(pt);
      index = parent.getComponentZOrder(c);
      if (c == parent || index < 0) {
        return;
      }
      draggingComponent = c;

      parent.remove(draggingComponent);
      parent.add(gap, index);
      parent.revalidate();
      parent.repaint();

      window.add(draggingComponent);
      window.pack();

      Dimension d = draggingComponent.getPreferredSize();
      Point p = new Point(pt.x - d.width / 2, pt.y - d.height / 2);
      SwingUtilities.convertPointToScreen(p, parent);
      window.setLocation(p);
      window.setVisible(true);

      return;
    }
    if (!window.isVisible() || draggingComponent == null) {
      return;
    }

    Dimension d = draggingComponent.getPreferredSize();
    Point p = new Point(pt.x - d.width / 2, pt.y - d.height / 2);
    SwingUtilities.convertPointToScreen(p, parent);
    window.setLocation(p);

    for (int i = 0; i < parent.getComponentCount(); i++) {
      Component c = parent.getComponent(i);
      Rectangle r = c.getBounds();
      Rectangle r1 = new Rectangle(r.x, r.y, r.width / 2, r.height);
      Rectangle r2 = new Rectangle(r.x + r.width / 2, r.y, r.width / 2, r.height);
      if (r1.contains(pt)) {
        if (c == gap) {
          return;
        }
        int n = i - 1 >= 0 ? i : 0;
        parent.remove(gap);
        parent.add(gap, n);
        parent.revalidate();
        parent.repaint();
        return;
      } else if (r2.contains(pt)) {
        if (c == gap) {
          return;
        }
        parent.remove(gap);
        parent.add(gap, i);
        parent.revalidate();
        parent.repaint();
        return;
      }
    }
    parent.remove(gap);
    parent.revalidate();
    parent.repaint();
  }

  @Override public void mouseReleased(MouseEvent e) {
    startPt = null;
    if (!window.isVisible() || draggingComponent == null) {
      return;
    }
    Point pt = e.getPoint();
    JComponent parent = (JComponent) e.getComponent();

    Component cmp = draggingComponent;
    draggingComponent = null;
    window.setVisible(false);

    for (int i = 0; i < parent.getComponentCount(); i++) {
      Component c = parent.getComponent(i);
      Rectangle r = c.getBounds();
      Rectangle r1 = new Rectangle(r.x, r.y, r.width / 2, r.height);
      Rectangle r2 = new Rectangle(r.x + r.width / 2, r.y, r.width / 2, r.height);
      if (r1.contains(pt)) {
        int n = i - 1 >= 0 ? i : 0;
        parent.remove(gap);
        parent.add(cmp, n);
        parent.revalidate();
        parent.repaint();
        return;
      } else if (r2.contains(pt)) {
        parent.remove(gap);
        parent.add(cmp, i);
        parent.revalidate();
        parent.repaint();
        return;
      }
    }
    if (parent.getBounds().contains(pt)) {
      parent.remove(gap);
      parent.add(cmp);
    } else {
      parent.remove(gap);
      parent.add(cmp, index);
    }
    parent.revalidate();
    parent.repaint();
  }
}

References

2008/12/15

Adding JPopupMenu to JToolBar-Button

Code

class MenuArrowIcon implements Icon {
  @Override public void paintIcon(Component c, Graphics g, int x, int y) {
    Graphics2D g2 = (Graphics2D) g.create();
    g2.setPaint(Color.BLACK);
    g2.translate(x, y);
    g2.drawLine(2, 3, 6, 3);
    g2.drawLine(3, 4, 5, 4);
    g2.drawLine(4, 5, 4, 5);
    g2.dispose();
  }

  @Override public int getIconWidth()  {
    return 9;
  }

  @Override public int getIconHeight() {
    return 9;
  }
}

class MenuToggleButton extends JToggleButton {
  private static final Icon ARROW_ICON = new MenuArrowIcon();
  private JPopupMenu popup;

  protected MenuToggleButton() {
    this("", null);
  }

  protected MenuToggleButton(Icon icon) {
    this("", icon);
  }

  protected MenuToggleButton(String text) {
    this(text, null);
  }

  protected MenuToggleButton(String text, Icon icon) {
    super();
    Action action = new AbstractAction(text) {
      @Override public void actionPerformed(ActionEvent e) {
        Component b = (Component) e.getSource();
        Optional.ofNullable(getPopupMenu()).ifPresent(p -> p.show(b, 0, b.getHeight()));
      }
    };
    action.putValue(Action.SMALL_ICON, icon);
    setAction(action);
    setFocusable(false);
    setBorder(BorderFactory.createEmptyBorder(4, 4, 4, 4 + ARROW_ICON.getIconWidth()));
  }

  public JPopupMenu getPopupMenu() {
    return popup;
  }

  public void setPopupMenu(JPopupMenu pop) {
    this.popup = pop;
    pop.addPopupMenuListener(new PopupMenuListener() {
      @Override public void popupMenuCanceled(PopupMenuEvent e) {
        /* not needed */
      }

      @Override public void popupMenuWillBecomeVisible(PopupMenuEvent e) {
        /* not needed */
      }

      @Override public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {
        setSelected(false);
      }
    });
  }

  @Override protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    Dimension dim = getSize();
    Insets ins = getInsets();
    int x = dim.width - ins.right;
    int y = ins.top + (dim.height - ins.top - ins.bottom - ARROW_ICON.getIconHeight()) / 2;
    ARROW_ICON.paintIcon(this, g, x, y);
  }
}

References