Google Tag Manager

2023/04/30

Change the tooltip of a tab in the JTabbedPane to a speech balloon shape, depending on the position of the tab.

Code

class BalloonToolTip extends JToolTip {
  private static final int SIZE = 4;
  private static final double ARC = 4d;
  private transient HierarchyListener listener;
  private transient Shape shape;

  @Override public void updateUI() {
    removeHierarchyListener(listener);
    super.updateUI();
    setLayout(new BorderLayout());
    listener = e -> {
      Component c = e.getComponent();
      if ((e.getChangeFlags() & HierarchyEvent.SHOWING_CHANGED) != 0
            && c.isShowing()) {
        Optional.ofNullable(SwingUtilities.getWindowAncestor(c))
            .filter(w -> w.getType() == Window.Type.POPUP)
            .ifPresent(w -> w.setBackground(new Color(0x0, true)));
      }
    };
    addHierarchyListener(listener);
    setOpaque(false);
    setBorder(BorderFactory.createEmptyBorder(SIZE, SIZE, SIZE, SIZE));
  }

  @Override public Dimension getPreferredSize() {
    Dimension d = super.getPreferredSize();
    d.width += SIZE;
    d.height += SIZE;
    return d;
  }

  @Override protected void paintComponent(Graphics g) {
    Graphics2D g2 = (Graphics2D) g.create();
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setColor(getBackground());
    g2.fill(shape);
    g2.setPaint(getForeground());
    g2.draw(shape);
    g2.dispose();
    // super.paintComponent(g);
  }

  public void updateBalloonShape(int placement) {
    Insets i = getInsets();
    Dimension d = getPreferredSize();
    Path2D tail = new Path2D.Double();
    double w = d.getWidth() - i.left - i.right - 1d;
    double h = d.getHeight() - i.top - i.bottom - 1d;
    double cx = w / 2d;
    double cy = h / 2d;
    switch (placement) {
      case SwingConstants.LEFT:
        tail.moveTo(0, cy - SIZE);
        tail.lineTo(-SIZE, cy);
        tail.lineTo(0, cy + SIZE);
        break;
      case SwingConstants.RIGHT:
        tail.moveTo(w, cy - SIZE);
        tail.lineTo(w + SIZE, cy);
        tail.lineTo(w, cy + SIZE);
        break;
      case SwingConstants.BOTTOM:
        tail.moveTo(cx - SIZE, h);
        tail.lineTo(cx, h + SIZE);
        tail.lineTo(cx + SIZE, h);
        break;
      default: // case SwingConstants.TOP:
        tail.moveTo(cx - SIZE, 0);
        tail.lineTo(cx, -SIZE);
        tail.lineTo(cx + SIZE, 0);
    }
    Area area = new Area(new RoundRectangle2D.Double(0, 0, w, h, ARC, ARC));
    area.add(new Area(tail));
    AffineTransform at = AffineTransform.getTranslateInstance(i.left, i.top);
    shape = at.createTransformedShape(area);
  }
}

JTabbedPane tabs = new JTabbedPane(
    SwingConstants.TOP, JTabbedPane.SCROLL_TAB_LAYOUT) {
  private transient BalloonToolTip tip;
  private final JLabel label = new JLabel(" ", CENTER);

  @Override public Point getToolTipLocation(MouseEvent e) {
    int idx = indexAtLocation(e.getX(), e.getY());
    String txt = idx >= 0 ? getToolTipTextAt(idx) : null;
    return Optional.ofNullable(txt).map(toolTipText -> {
      JToolTip tips = createToolTip();
      tips.setTipText(toolTipText);
      label.setText(toolTipText);
      if (tips instanceof BalloonToolTip) {
        ((BalloonToolTip) tips).updateBalloonShape(getTabPlacement());
      }
      return getToolTipPoint(
          getBoundsAt(idx), tips.getPreferredSize());
    }).orElse(null);
  }

  private Point getToolTipPoint(Rectangle r, Dimension d) {
    double dx;
    double dy;
    switch (getTabPlacement()) {
      case LEFT:
        dx = r.getMaxX();
        dy = r.getCenterY() - d.getHeight() / 2d;
        break;
      case RIGHT:
        dx = r.getMinX() - d.width;
        dy = r.getCenterY() - d.getHeight() / 2d;
        break;
      case BOTTOM:
        dx = r.getCenterX() - d.getWidth() / 2d;
        dy = r.getMinY() - d.height;
        break;
      default: // case TOP:
        dx = r.getCenterX() - d.getWidth() / 2d;
        dy = r.getMaxY();
    }
    return new Point((int) (dx + .5), (int) (dy + .5));
  }

  @Override public JToolTip createToolTip() {
    if (tip == null) {
      tip = new BalloonToolTip();
      LookAndFeel.installColorsAndFont(
          label,
          "ToolTip.background",
          "ToolTip.foreground",
          "ToolTip.font");
      tip.add(label);
      tip.updateBalloonShape(getTabPlacement());
      tip.setComponent(this);
    }
    return tip;
  }

  @Override public void updateUI() {
    tip = null;
    super.updateUI();
  }
};

References

2023/03/31

Create a dot matrix LED digital clock with JList

Code

private static JList<Boolean> makeLedDotMatrixList(
    ListModel<Boolean> model, Dimension dim) {
  return new JList<Boolean>(model) {
    @Override public void updateUI() {
      setFixedCellWidth(dim.width);
      setFixedCellHeight(dim.height);
      setVisibleRowCount(ROW);
      setCellRenderer(null);
      super.updateUI();
      setLayoutOrientation(JList.VERTICAL_WRAP);
      setFocusable(false);
      ListCellRenderer<? super Boolean> renderer = getCellRenderer();
      Icon on = new LedDotIcon(true, dim);
      Icon off = new LedDotIcon(false, dim);
      setCellRenderer((list, value, index, isSelected, cellHasFocus) -> {
        Component c = renderer.getListCellRendererComponent(
            list, null, index, false, false);
        if (c instanceof JLabel) {
          ((JLabel) c).setIcon(Objects.equals(Boolean.TRUE, value) ? on : off);
        }
        return c;
      });
      setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));
      setBackground(Color.BLACK);
    }
  };
}

class LedDotIcon implements Icon {
  private final Color on = new Color(0x32_FF_AA);
  private final boolean led;
  private final Dimension dim;

  protected LedDotIcon(boolean led, Dimension dim) {
    this.led = led;
    this.dim = dim;
  }

  @Override public void paintIcon(Component c, Graphics g, int x, int y) {
    Graphics2D g2 = (Graphics2D) g.create();
    g2.setRenderingHint(
        RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
    // JList#setLayoutOrientation(VERTICAL_WRAP) + Synth, Nimbus, GTK bug???
    // g2.translate(x, y);
    g2.setPaint(led ? on : c.getBackground());
    g2.fillOval(0, 0, getIconWidth() - 1, getIconHeight() - 1);
    g2.dispose();
  }

  @Override public int getIconWidth() {
    return dim.width;
  }

  @Override public int getIconHeight() {
    return dim.height;
  }
}

DefaultListModel<Boolean> model1 = new DefaultListModel<Boolean>() {
  @Override public Boolean getElementAt(int index) {
    return getHoursMinutesDotMatrix(time, index);
  }
};
model1.setSize((COLUMN * 4 + 5) * ROW);

private static boolean getHoursMinutesDotMatrix(LocalTime time, int index) {
  int ten = 10;
  int hours = time.getHour();
  int h1 = hours / ten;
  int start = 0;
  int end = start + COLUMN;
  if (contains(index, start, end, h1)) {
    return hours >= ten;
  }
  int gap = 1;
  int h2 = hours - h1 * ten;
  start = end + gap;
  end = start + COLUMN;
  if (contains(index, start, end, h2)) {
    return true;
  }
  int seconds = time.getSecond();
  int s1 = seconds / ten;
  int s2 = seconds - s1 * ten;
  start = end + gap;
  end = start + gap;
  if (index < end * ROW && s2 % 2 == 0 && DOT.contains(index - start * ROW)) {
    return true;
  }
  int minutes = time.getMinute();
  int m1 = minutes / ten;
  start = end + gap;
  end = start + COLUMN;
  if (contains(index, start, end, m1)) {
    return true;
  }
  int m2 = minutes - m1 * ten;
  start = end + gap;
  end = start + COLUMN;
  return contains(index, start, end, m2);
}

private static final int COLUMN = 4;
private static final int ROW = 7;
private static final List<Set<Integer>> NUMBERS = Arrays.asList(
  Set.of(0, 1, 2, 3, 4, 5, 6, 7, 13, 14, 20, 21, 22, 23, 24, 25, 26, 27), // 0
  Set.of(21, 22, 23, 24, 25, 26, 27), // 1
  Set.of(0, 3, 4, 5, 6, 7, 10, 13, 14, 17, 20, 21, 22, 23, 24, 27), // 2
  Set.of(0, 3, 6, 7, 10, 13, 14, 17, 20, 21, 22, 23, 24, 25, 26, 27), // 3
  Set.of(0, 1, 2, 3, 10, 17, 21, 22, 23, 24, 25, 26, 27), // 4
  Set.of(0, 1, 2, 3, 6, 7, 10, 13, 14, 17, 20, 21, 24, 25, 26, 27), // 5
  Set.of(0, 1, 2, 3, 4, 5, 6, 7, 10, 13, 14, 17, 20, 21, 24, 25, 26, 27), // 6
  Set.of(0, 1, 2, 3, 7, 14, 21, 22, 23, 24, 25, 26, 27), // 7
  Set.of(0, 1, 2, 3, 4, 5, 6, 7, 10, 13, 14, 17, 20, 21, 22, 23, 24, 25, 26, 27), // 8
  Set.of(0, 1, 2, 3, 6, 7, 10, 13, 14, 17, 20, 21, 22, 23, 24, 25, 26, 27)); // 9

Code(alternative pattern)

private static final int COLUMN = 5;
private static final int ROW = 7;
private static final List> NUMBERS = Arrays.asList(
    Set.of(1, 2, 3, 4, 5, 7, 9, 13, 14, 17, 20, 21, 25, 27, 29, 30, 31, 32, 33), // 0
    Set.of(8, 13, 14, 15, 16, 17, 18, 19, 20, 27), // 1
    Set.of(1, 6, 7, 12, 13, 14, 18, 20, 21, 24, 27, 29, 30, 34), // 2
    Set.of(0, 5, 7, 13, 14, 17, 20, 21, 23, 24, 27, 28, 29, 32, 33), // 3
    Set.of(3, 4, 9, 11, 15, 18, 21, 22, 23, 24, 25, 26, 27, 32), // 4
    Set.of(0, 1, 2, 5, 7, 9, 13, 14, 16, 20, 21, 23, 27, 28, 31, 32, 33), // 5
    Set.of(1, 2, 3, 4, 5, 7, 10, 13, 14, 17, 20, 21, 24, 27, 29, 32, 33), // 6
    Set.of(0, 7, 11, 12, 13, 14, 17, 21, 23, 28, 29), // 7
    Set.of(1, 2, 4, 5, 7, 10, 13, 14, 17, 20, 21, 24, 27, 29, 30, 32, 33), // 8
    Set.of(1, 2, 5, 7, 10, 13, 14, 17, 20, 21, 24, 27, 29, 30, 31, 32, 33)); // 9

References

2023/02/28

Draw a projection-transformed regular hexahedron wireframe in JPanel and rotate it in space by mouse dragging

Code

class Vertex {
  private double dx;
  private double dy;
  private double dz;
  public double vx;
  public double vy;

  protected Vertex(double dx, double dy, double dz) {
    this.dx = dx;
    this.dy = dy;
    this.dz = dz;
    projectionTransformation();
  }

  private void projectionTransformation() {
    double screenDistance = 500d;
    double depth = 1000d;
    double gz = dz + depth;
    this.vx = screenDistance * dx / gz;
    this.vy = screenDistance * dy / gz;
  }

  public void rotateTransformation(double kx, double ky, double kz) {
    double x0 = dx * Math.cos(ky) - dz * Math.sin(ky);
    double y0 = dy;
    double z0 = dx * Math.sin(ky) + dz * Math.cos(ky);
    double y1 = y0 * Math.cos(kx) - z0 * Math.sin(kx);
    double z1 = y0 * Math.sin(kx) + z0 * Math.cos(kx);
    this.dx = x0 * Math.cos(kz) - y1 * Math.sin(kz);
    this.dy = x0 * Math.sin(kz) + y1 * Math.cos(kz);
    this.dz = z1;
    projectionTransformation();
  }
}

// ...
List<Vertex> cube = new ArrayList<>(8);
double sideLength = 100;
cube.add(new Vertex(sideLength, sideLength, sideLength));
cube.add(new Vertex(sideLength, sideLength, -sideLength));
cube.add(new Vertex(-sideLength, sideLength, -sideLength));
cube.add(new Vertex(-sideLength, sideLength, sideLength));
cube.add(new Vertex(sideLength, -sideLength, sideLength));
cube.add(new Vertex(sideLength, -sideLength, -sideLength));
cube.add(new Vertex(-sideLength, -sideLength, -sideLength));
cube.add(new Vertex(-sideLength, -sideLength, sideLength));

// ...
// Projection transformation of each vertex of a regular hexahedron by moving the viewpoint to the origin, the distance to the screen to 500, and the z-axis coordinate value to the back of the screen to 1000.
// Draw a wireframe in the center of the JPanel by connecting the transformed vertex coordinates with Path2D
@Override protected void paintComponent(Graphics g) {
  super.paintComponent(g);
  Graphics2D g2 = (Graphics2D) g.create();
  g2.setRenderingHint(
    RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  Path2D path = new Path2D.Double();
  path.moveTo(cube.get(0).vx, cube.get(0).vy);
  path.lineTo(cube.get(1).vx, cube.get(1).vy);
  path.lineTo(cube.get(2).vx, cube.get(2).vy);
  path.lineTo(cube.get(3).vx, cube.get(3).vy);
  path.lineTo(cube.get(0).vx, cube.get(0).vy);
  path.lineTo(cube.get(4).vx, cube.get(4).vy);
  path.lineTo(cube.get(5).vx, cube.get(5).vy);
  path.lineTo(cube.get(6).vx, cube.get(6).vy);
  path.lineTo(cube.get(7).vx, cube.get(7).vy);
  path.lineTo(cube.get(4).vx, cube.get(4).vy);
  path.moveTo(cube.get(1).vx, cube.get(1).vy);
  path.lineTo(cube.get(5).vx, cube.get(5).vy);
  path.moveTo(cube.get(2).vx, cube.get(2).vy);
  path.lineTo(cube.get(6).vx, cube.get(6).vy);
  path.moveTo(cube.get(3).vx, cube.get(3).vy);
  path.lineTo(cube.get(7).vx, cube.get(7).vy);
  Rectangle r = SwingUtilities.calculateInnerArea(this, null);
  g2.setPaint(Color.WHITE);
  g2.fill(r);
  g2.translate(r.getCenterX(), r.getCenterY());
  g2.setPaint(Color.BLACK);
  g2.draw(path);
  g2.dispose();
}

// ...
// Add the following `MouseAdapter` to the `JPanel` that transforms and draws the projection of the regular hexahedron, and rotate each vertex in the space
private class DragRotateHandler extends MouseAdapter {
  private final Cursor defCursor = Cursor.getDefaultCursor();
  private final Cursor hndCursor = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
  private final Point pp = new Point();

  @Override public void mouseDragged(MouseEvent e) {
    Point pt = e.getPoint();
    double rotY = (pt.x - pp.x) * .03;
    double rotX = (pt.y - pp.y) * .03;
    double rotZ = 0d;
    for (Vertex v : cube) {
      v.rotateTransformation(rotX, rotY, rotZ);
    }
    pp.setLocation(pt);
    e.getComponent().repaint();
  }

  @Override public void mousePressed(MouseEvent e) {
    e.getComponent().setCursor(hndCursor);
    pp.setLocation(e.getPoint());
  }

  @Override public void mouseReleased(MouseEvent e) {
    e.getComponent().setCursor(defCursor);
  }
}

References

2023/01/31

Create numbers for a 7-segment digital clock using Path2D

Code

class DigitalNumber {
  private final double isosceles;
  private final double dx;
  private final double dy;
  private final double width;
  private final double height;
  private final Rectangle rect = new Rectangle();
  public static final Color OFF = new Color(0xCC_CC_CC);
  public static final Color ON = Color.DARK_GRAY;
  public static final Color BGC = Color.LIGHT_GRAY;
  private final List<Set<Seg>> numbers = Arrays.asList(
      EnumSet.of(Seg.A, Seg.B, Seg.C, Seg.D, Seg.E, Seg.F),
      EnumSet.of(Seg.B, Seg.C),
      EnumSet.of(Seg.A, Seg.B, Seg.D, Seg.E, Seg.G),
      EnumSet.of(Seg.A, Seg.B, Seg.C, Seg.D, Seg.G),
      EnumSet.of(Seg.B, Seg.C, Seg.F, Seg.G),
      EnumSet.of(Seg.A, Seg.C, Seg.D, Seg.F, Seg.G),
      EnumSet.of(Seg.A, Seg.C, Seg.D, Seg.E, Seg.F, Seg.G),
      EnumSet.of(Seg.A, Seg.B, Seg.C),
      EnumSet.of(Seg.A, Seg.B, Seg.C, Seg.D, Seg.E, Seg.F, Seg.G),
      EnumSet.of(Seg.A, Seg.B, Seg.C, Seg.D, Seg.F, Seg.G));
  private Set<Seg> led = EnumSet.noneOf(Seg.class);

  protected DigitalNumber(double dx, double dy, double isosceles) {
    this.isosceles = isosceles;
    this.dx = dx;
    this.dy = dy;
    this.width = 2d * isosceles;
    this.height = width + isosceles;
    rect.setLocation((int) dx, (int) dy);
    rect.setSize((int) (width + 3 * isosceles), (int) (height * 2));
  }

  public Rectangle getBounds() {
    return rect;
  }

  public void setNumber(int num) {
    led = numbers.get(num);
  }

  public void turnOffNumber() {
    led.clear();
  }

  public void drawNumber(Graphics2D g2) {
    EnumSet.allOf(Seg.class).forEach(s -> {
      g2.setColor(led.contains(s) ? ON : OFF);
      Shape seg = s.getShape(dx, dy, width, height, isosceles);
      g2.fill(seg);
      g2.setColor(BGC);
      g2.draw(seg);
    });
  }
}

enum Seg { A, B, C, D, E, F, G }

References

2022/12/31

Inverse the display position of JSlider's ticks and knobs

Code

class VerticalFlipLayerUI extends LayerUI<JComponent> {
  @Override public void paint(Graphics g, JComponent c) {
    if (c instanceof JLayer) {
      Graphics2D g2 = (Graphics2D) g.create();
      g2.setTransform(getAffineTransform(c.getSize()));
      super.paint(g2, c);
      g2.dispose();
    } else {
      super.paint(g, c);
    }
  }

  @Override public void installUI(JComponent c) {
    super.installUI(c);
    if (c instanceof JLayer) {
      JLayer<?> l = (JLayer<?>) c;
      l.setLayerEventMask(
          AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK);
    }
  }

  @Override public void uninstallUI(JComponent c) {
    if (c instanceof JLayer) {
      ((JLayer<?>) c).setLayerEventMask(0);
    }
    super.uninstallUI(c);
  }

  @Override public void eventDispatched(
        AWTEvent e, JLayer<? extends JComponent> l) {
    if (e instanceof MouseEvent) {
      MouseEvent me = (MouseEvent) e;
      Point2D pt = me.getPoint();
      try {
        pt = getAffineTransform(l.getSize()).inverseTransform(pt, null);
      } catch (NoninvertibleTransformException ex) {
        ex.printStackTrace();
        UIManager.getLookAndFeel().provideErrorFeedback(me.getComponent());
      }
      // Horizontal: me.translatePoint((int) pt.getX() - me.getX(), 0);
      me.translatePoint(0, (int) pt.getY() - me.getY());
      me.getComponent().repaint();
    }
    super.eventDispatched(e, l);
  }

  private AffineTransform getAffineTransform(Dimension d) {
    AffineTransform at = AffineTransform.getTranslateInstance(0d, d.height);
    at.scale(1d, -1d);
    return at;
  }
}

References