Google Tag Manager

2024/02/29

Paint JMenuItem selection rollover with rounded rectangle

Code

class BasicRoundMenuItemUI extends BasicMenuItemUI {
  @Override protected void paintBackground(
      Graphics g, JMenuItem menuItem, Color bgColor) {
    ButtonModel m = menuItem.getModel();
    Color oldColor = g.getColor();
    int menuWidth = menuItem.getWidth();
    int menuHeight = menuItem.getHeight();
    if (menuItem.isOpaque()) {
      if (m.isArmed() || (menuItem instanceof JMenu && m.isSelected())) {
        Graphics2D g2 = (Graphics2D) g.create();
        g2.setRenderingHint(
          RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        // g2.clearRect(0, 0, menuWidth, menuHeight);
        g2.setPaint(menuItem.getBackground());
        g2.fillRect(0, 0, menuWidth, menuHeight);
        g2.setColor(bgColor);
        g2.fillRoundRect(2, 2, menuWidth - 4, menuHeight - 4, 8, 8);
        g2.dispose();
      } else {
        g.setColor(menuItem.getBackground());
        g.fillRect(0, 0, menuWidth, menuHeight);
      }
      g.setColor(oldColor);
    } else if (m.isArmed() || (menuItem instanceof JMenu && m.isSelected())) {
      g.setColor(bgColor);
      g.fillRoundRect(2, 2, menuWidth - 4, menuHeight - 4, 8, 8);
      g.setColor(oldColor);
    }
  }
}

References

2024/01/31

Paint a JProgressBar with indeterminate progress status in a cell of a JTable

Code

private final JTable table = new JTable(model) {
  @Override public void updateUI() {
    super.updateUI();
    removeColumn(getColumnModel().getColumn(3));
    JProgressBar progress = new JProgressBar();
    TableCellRenderer renderer = new DefaultTableCellRenderer();
    TableColumn tc = getColumnModel().getColumn(2);
    tc.setCellRenderer((tbl, value, isSelected, hasFocus, row, column) -> {
      Component c;
      if (value instanceof JProgressBar) {
        c = (JProgressBar) value;
      } else if (value instanceof Integer) {
        progress.setValue((int) value);
        c = progress;
      } else {
        c = renderer.getTableCellRendererComponent(
            tbl, Objects.toString(value), isSelected, hasFocus, row, column);
      }
      return c;
    });
  }
};

class IndeterminateProgressBarUI extends BasicProgressBarUI {
  @Override public void incrementAnimationIndex() {
    super.incrementAnimationIndex();
  }
}

class BackgroundTask extends SwingWorker<Integer, Object> {
  private final Random rnd = new Random();

  @Override protected Integer doInBackground() throws InterruptedException {
    int lengthOfTask = calculateTaskSize();
    int current = 0;
    int total = 0;
    while (current <= lengthOfTask && !isCancelled()) {
      publish(100 * current / lengthOfTask);
      total += doSomething();
      current++;
    }
    return total;
  }

  private int calculateTaskSize() throws InterruptedException {
    int total = 0;
    JProgressBar indeterminate = new JProgressBar() {
      @Override public void updateUI() {
        super.updateUI();
        setUI(new IndeterminateProgressBarUI());
      }
    };
    indeterminate.setIndeterminate(true);
    // Indeterminate loop:
    for (int i = 0; i < 200; i++) {
      int iv = rnd.nextInt(50) + 1;
      Thread.sleep(iv);
      ProgressBarUI ui = indeterminate.getUI()
      ((IndeterminateProgressBarUI) ui).incrementAnimationIndex();
      publish(indeterminate);
      total += iv;
    }
    return 1 + total / 100;
  }

  private int doSomething() throws InterruptedException {
    int iv = rnd.nextInt(50) + 1;
    Thread.sleep(iv);
    return iv;
  }
}

References

2023/12/31

Create a 4-digit numeric PIN code input field using JPasswordField

Code

class PinCodeDocumentFilter extends DocumentFilter {
  public static final int MAX = 4;

  @Override public void replace(
      DocumentFilter.FilterBypass fb, int offset,
      int length, String text, AttributeSet attrs) throws BadLocationException {
    String str = fb.getDocument().getText(
      0, fb.getDocument().getLength()) + text;
    if (str.length() <= MAX && str.matches("\\d+")) {
      super.replace(fb, offset, length, text, attrs);
    }
  }
}

class PasswordView2 extends PasswordView {
  public PasswordView2(Element elem) {
    super(elem);
  }

  @Override protected int drawUnselectedText(
      Graphics g, int x, int y, int p0, int p1) throws BadLocationException {
    return drawText(g, x, y, p0, p1);
  }

  // @see drawUnselectedTextImpl(...)
  private int drawText(Graphics g, int x, int y, int p0, int p1)
        throws BadLocationException {
    Container c = getContainer();
    int j = x;
    if (c instanceof JPasswordField) {
      JPasswordField f = (JPasswordField) c;
      if (f.isEnabled()) {
        g.setColor(f.getForeground());
      } else {
        g.setColor(f.getDisabledTextColor());
      }
      Graphics2D g2 = (Graphics2D) g;
      char echoChar = f.getEchoChar();
      int n = p1 - p0;
      // Override BasicPasswordFieldUI#create(Element) to return PasswordView2
      // that makes only trailing digits visible without masking
      for (int i = 0; i < n; i++) {
        j = i == n - 1
            ? drawLastChar(g2, j, y, i)
            : drawEchoCharacter(g, j, y, echoChar);
      }
    }
    return j;
  }

  private int drawLastChar(Graphics g, int x, int y, int p1)
        throws BadLocationException {
    Graphics2D g2 = (Graphics2D) g;
    Font font = g2.getFont();
    float fs = font.getSize2D();
    double w = font.getStringBounds("0", g2.getFontRenderContext()).getWidth();
    int sz = (int) ((fs - w) / 2d);
    Document doc = getDocument();
    Segment s = new Segment(); // SegmentCache.getSharedSegment();
    doc.getText(p1, 1, s);
    // int ret = Utilities.drawTabbedText(s, x, y, g, this, p1);
    // SegmentCache.releaseSharedSegment(s);
    return Utilities.drawTabbedText(s, x + sz, y, g, this, p1);
  }
}

References

2023/11/30

Split TableColumn of JTableHeader with diagonal line Border

Code

int size = 32;
JTable table = new JTable(model) {
  @Override public void updateUI() {
    super.updateUI();
    setRowHeight(size);
    TableCellRenderer hr = new VerticalTableHeaderRenderer();
    TableColumnModel cm = getColumnModel();
    cm.getColumn(0).setHeaderRenderer(
        new DiagonallySplitHeaderRenderer());
    cm.getColumn(0).setPreferredWidth(size * 5);
    for (int i = 1; i < cm.getColumnCount(); i++) {
      TableColumn tc = cm.getColumn(i);
      tc.setHeaderRenderer(hr);
      tc.setPreferredWidth(size);
    }
  }
};
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

JScrollPane scroll = new JScrollPane(table);
scroll.setColumnHeader(new JViewport() {
  @Override public Dimension getPreferredSize() {
    Dimension d = super.getPreferredSize();
    d.height = size * 2;
    return d;
  }
});
// ...

class DiagonallySplitBorder extends MatteBorder {
  protected DiagonallySplitBorder(
      int top, int left, int bottom, int right, Color matteColor) {
    super(top, left, bottom, right, matteColor);
  }

  @Override public void paintBorder(
      Component c, Graphics g, int x, int y, int width, int height) {
    super.paintBorder(c, g, x, y, width, height);
    Graphics2D g2 = (Graphics2D) g.create();
    g2.translate(x, y);
    g2.setRenderingHint(
        RenderingHints.KEY_ANTIALIASING,
        RenderingHints.VALUE_ANTIALIAS_ON);
    g2.setPaint(getMatteColor());
    g2.drawLine(0, 0, c.getWidth() - 1, c.getHeight() - 1);
    g2.dispose();
  }
}

References

2023/10/31

Sort JTable rows with multiple conditions

Code

RowSorter<? extends TableModel> sorter = table.getRowSorter();
if (sorter instanceof TableRowSorter) {
  TableRowSorter<? extends TableModel> rs
      = (TableRowSorter<? extends TableModel>) sorter;
  rs.setComparator(0, Comparator.comparing(RowData::getPosition));
  rs.setComparator(1, Comparator.comparing(RowData::getTeam));
  rs.setComparator(2, Comparator.comparing(RowData::getMatches));
  rs.setComparator(3, Comparator.comparing(RowData::getWins));
  rs.setComparator(4, Comparator.comparing(RowData::getDraws));
  rs.setComparator(5, Comparator.comparing(RowData::getLosses));
  rs.setComparator(6, Comparator.comparing(RowData::getGoalsFor));
  rs.setComparator(7, Comparator.comparing(RowData::getGoalsAgainst));
  rs.setComparator(8, Comparator.comparing(RowData::getGoalDifference));
  rs.setComparator(9, Comparator.comparing(RowData::getPoints)
      .thenComparing(RowData::getGoalDifference));
}
add(new JScrollPane(table));

References