Google Tag Manager

2022/04/30

Disable the arrow button when the knob position of the JScrollBar is on the boundary

Code

// UIManager.put("ScrollBar.alwaysShowThumb", Boolean.TRUE);
JScrollPane scroll = new JScrollPane(new JTable(24, 3));
scroll.getVerticalScrollBar().addAdjustmentListener(e -> {
  JScrollBar scrollBar = (JScrollBar) e.getAdjustable();
  BoundedRangeModel m = scrollBar.getModel();
  int value = m.getValue();
  boolean max = value == m.getMaximum() - m.getExtent();
  Optional.ofNullable(scrollBar.getComponent(0))
      .ifPresent(b -> b.setEnabled(!max));
  boolean min = value == m.getMinimum();
  Optional.ofNullable(scrollBar.getComponent(1))
      .ifPresent(b -> b.setEnabled(!min));
});

References

2022/03/30

Paint the major tick marks inside the JSlider track and the current value inside the knob

Code

JSlider slider = new JSlider();
slider.setSnapToTicks(true);
slider.setMajorTickSpacing(10);
slider.addMouseMotionListener(new MouseAdapter() {
  @Override public void mouseDragged(MouseEvent e) {
    super.mouseDragged(e);
    e.getComponent().repaint();
  }
});

UIDefaults d = new UIDefaults();
d.put("Slider.thumbWidth", 24);
d.put("Slider.thumbHeight", 24);
Painter<JSlider> thumbPainter = (g, c, w, h) -> {
  g.setPaint(new Color(0x21_98_F6));
  g.fillOval(0, 0, w, h);
  NumberIcon icon = new NumberIcon(c.getValue());
  int xx = (w - icon.getIconWidth()) / 2;
  int yy = (h - icon.getIconHeight()) / 2;
  icon.paintIcon(c, g, xx, yy);
};
d.put("Slider:SliderThumb[Disabled].backgroundPainter", thumbPainter);
d.put("Slider:SliderThumb[Enabled].backgroundPainter", thumbPainter);
d.put("Slider:SliderThumb[Focused+MouseOver].backgroundPainter", thumbPainter);
d.put("Slider:SliderThumb[Focused+Pressed].backgroundPainter", thumbPainter);
d.put("Slider:SliderThumb[Focused].backgroundPainter", thumbPainter);
d.put("Slider:SliderThumb[MouseOver].backgroundPainter", thumbPainter);
d.put("Slider:SliderThumb[Pressed].backgroundPainter", thumbPainter);

d.put("Slider:SliderTrack[Enabled].backgroundPainter", new Painter<JSlider>() {
  @Override public void paint(Graphics2D g, JSlider c, int w, int h) {
    int arc = 10;
    int thumbSize = 24;
    int trackHeight = 8;
    int tickSize = 4;
    int trackWidth = w - thumbSize;
    int fillTop = (thumbSize - trackHeight) / 2;
    int fillLeft = thumbSize / 2;

    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g.setColor(new Color(0xC6_E4_FC));
    g.fillRoundRect(fillLeft, fillTop + 2, trackWidth, trackHeight - 4, arc, arc);

    // Paint track
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    g.setColor(new Color(0xC6_E4_FC));
    g.fillRoundRect(fillLeft, fillTop + 2, trackWidth, trackHeight - 4, arc, arc);

    int fillBottom = fillTop + trackHeight;
    Rectangle r = new Rectangle(fillLeft, fillTop, trackWidth, fillBottom - fillTop);

    // Paint the major tick marks on the track
    g.setColor(new Color(0x31_A8_F8));
    int value = c.getMinimum();
    while (value <= c.getMaximum()) {
      int xpt = getXPositionForValue(c, r, value);
      g.fillOval(xpt, (int) r.getCenterY() - tickSize / 2, tickSize, tickSize);
      // Overflow checking
      if (Integer.MAX_VALUE - c.getMajorTickSpacing() < value) {
        break;
      }
      value += c.getMajorTickSpacing();
    }

    // JSlider.isFilled
    int fillRight = getXPositionForValue(c, r, c.getValue());
    g.setColor(new Color(0x21_98_F6));
    g.fillRoundRect(fillLeft, fillTop, fillRight - fillLeft, fillBottom - fillTop, arc, arc);
  }

  // @see javax/swing/plaf/basic/BasicSliderUI#xPositionForValue(int value)
  private int getXPositionForValue(JSlider slider, Rectangle trackRect, float value) {
    float min = slider.getMinimum();
    float max = slider.getMaximum();
    float pixelsPerValue = trackRect.width / (max - min);
    int trackLeft = trackRect.x;
    int trackRight = trackRect.x + trackRect.width - 1;
    int pos = trackLeft + Math.round(pixelsPerValue * (value - min));
    return Math.max(trackLeft, Math.min(trackRight, pos));
  }
});
slider.putClientProperty("Nimbus.Overrides", d);

References

2022/02/28

Create a new JFrame when the JTabbedPane tab is dropped outside the frame

Code

class TabDragSourceListener implements DragSourceListener {
  @Override public void dragEnter(DragSourceDragEvent e) {
    e.getDragSourceContext().setCursor(DragSource.DefaultMoveDrop);
  }

  @Override public void dragExit(DragSourceEvent e) {
    e.getDragSourceContext().setCursor(DragSource.DefaultMoveNoDrop);
  }

  @Override public void dragDropEnd(DragSourceDropEvent e) {
    Component c = e.getDragSourceContext().getComponent();
    JRootPane root = ((JComponent) c).getRootPane();
    Class<GhostGlassPane> clz = GhostGlassPane.class;
    Optional.ofNullable(root.getGlassPane())
        .filter(clz::isInstance).map(clz::cast)
        .ifPresent(p -> p.setVisible(false));
    boolean dropSuccess = e.getDropSuccess();
    Window w = SwingUtilities.getWindowAncestor(c);
    boolean outOfFrame = !w.getBounds().contains(e.getLocation());
    if (dropSuccess && outOfFrame && c instanceof DnDTabbedPane) {
      DnDTabbedPane src = (DnDTabbedPane) c;
      int index = src.dragTabIndex;
      final Component cmp = src.getComponentAt(index);
      final Component tab = src.getTabComponentAt(index);
      final String title = src.getTitleAt(index);
      final Icon icon = src.getIconAt(index);
      final String tip = src.getToolTipTextAt(index);
      src.remove(index);
      DnDTabbedPane tabs = new DnDTabbedPane();
      tabs.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
      tabs.addTab(title, icon, cmp, tip);
      tabs.setTabComponentAt(0, tab);
      JFrame frame = new JFrame();
      frame.getContentPane().add(tabs);
      frame.setSize(320, 240);
      frame.setLocation(e.getLocation());
      frame.setVisible(true);
    }
  }

  @Override public void dropActionChanged(DragSourceDragEvent e) {
    /* not needed */
  }

  @Override public void dragOver(DragSourceDragEvent e) {
    /* not needed */
  }
}

References

2022/01/31

Fix the JToolTip display of JList cells to correspond to after mouse wheel rotation

Code

JList<String> list1 = new JList<String>(model) {
  @Override public void updateUI() {
    super.updateUI();
    setCellRenderer(new TooltipListCellRenderer<>());
  }
};
JScrollPane scroll1 = new JScrollPane(list1);
scroll1.addMouseWheelListener(e -> {
  JScrollPane scrollPane = (JScrollPane) e.getComponent();
  Component view = scrollPane.getViewport().getView();
  MouseEvent event = SwingUtilities.convertMouseEvent(scrollPane, e, view);
  ToolTipManager.sharedInstance().mouseMoved(event);
});

References

2022/01/01

Change the selection focus Border of JTabbedPane to underline

Code

class UnderlineFocusTabbedPane extends JTabbedPane {
  private static final Border DEFAULT_BORDER =
      BorderFactory.createMatteBorder(0, 0, 3, 0, new Color(0x0, true));
  private static final Border SELECTED_BORDER =
      BorderFactory.createMatteBorder(0, 0, 3, 0, new Color(0x00_AA_FF));

  protected UnderlineFocusTabbedPane() {
    super();
  }

  @Override public void updateUI() {
    super.updateUI();
    // setFocusable(false);
    if (getUI() instanceof WindowsTabbedPaneUI) {
      setUI(new WindowsTabbedPaneUI() {
        @Override protected void paintFocusIndicator(
            Graphics g, int tabPlacement, Rectangle[] rects, int tabIndex,
            Rectangle iconRect, Rectangle textRect, boolean isSelected) {
          super.paintFocusIndicator(g, tabPlacement, rects, tabIndex, iconRect, textRect, false);
        }
      });
    } else {
      setUI(new BasicTabbedPaneUI() {
        @Override protected void paintFocusIndicator(
            Graphics g, int tabPlacement, Rectangle[] rects, int tabIndex,
            Rectangle iconRect, Rectangle textRect, boolean isSelected) {
          super.paintFocusIndicator(g, tabPlacement, rects, tabIndex, iconRect, textRect, false);
        }
      });
    }
    addChangeListener(e -> {
      JTabbedPane tabbedPane = (JTabbedPane) e.getSource();
      if (tabbedPane.getTabCount() <= 0) {
        return;
      }
      int idx = tabbedPane.getSelectedIndex();
      for (int i = 0; i < tabbedPane.getTabCount(); i++) {
        Component c = tabbedPane.getTabComponentAt(i);
        if (c instanceof JComponent) {
          ((JComponent) c).setBorder(i == idx ? SELECTED_BORDER : DEFAULT_BORDER);
        }
      }
    });
  }

  @Override public void insertTab(
      String title, Icon icon, Component component, String tip, int index) {
    super.insertTab(title, icon, component, tip, index);
    JLabel label = new JLabel(title, icon, SwingConstants.CENTER);
    setTabComponentAt(index, label);
  }
}

References