概要

JSpinnerのテキストフィールド内に選択や編集ができない文字列を追加します。

サンプルコード

class StringBorder implements Border {
  private final JComponent parent;
  private final Insets insets;
  private final Rectangle rect;
  private final String str;

  public StringBorder(JComponent parent, String str) {
    this.parent = parent;
    this.str = str;
    FontRenderContext frc = new FontRenderContext(null, true, true);
    rect = parent.getFont().getStringBounds(str, frc).getBounds();
    insets = new Insets(0, 0, 0, rect.width);
  }

  @Override public Insets getBorderInsets(Component c) {
    return insets;
  }

  @Override public boolean isBorderOpaque() {
    return false;
  }

  @Override public void paintBorder(
      Component c, Graphics g, int x, int y, int width, int height) {
    Graphics2D g2 = (Graphics2D) g;
    float tx = x + width - rect.width;
    float ty = y - rect.y + (height - rect.height) / 2;
    // g2.setPaint(Color.RED);
    g2.drawString(str, tx, ty);
  }
}
View in GitHub: Java, Kotlin

解説

  • JSpinner.NumberEditor + DecimalFormat
    • JSpinnerの値をパーセントで指定
      JSpinner spinner1 = new JSpinner(new SpinnerNumberModel(0, 0, 1, 0.01));
      JSpinner.NumberEditor editor1 = new JSpinner.NumberEditor(spinner1, "0%");
      spinner1.setEditor(editor1);
      
  • JSpinner + StringBorder
    • JSpinnerのエディタに設定した余白内に文字列を描画
      JSpinner spinner2 = new JSpinner(new SpinnerNumberModel(0, 0, 100, 1));
      JSpinner.NumberEditor editor2 = new JSpinner.NumberEditor(spinner2);
      spinner2.setEditor(editor2);
      editor2.setOpaque(true);
      editor2.setBackground(Color.WHITE);
      // Border b = new StringBorder(editor2, "percent");
      Border b = new StringBorder(editor2, "%");
      Border c = editor2.getBorder();
      editor2.setBorder((c == null) ? b : BorderFactory.createCompoundBorder(c, b));
      
  • 以下のようにJLabelを余白に描画する方法もある
    • Component Border ≪ Java Tips Weblog
      JLabel label = new JLabel("%");
      label.setBorder(BorderFactory.createEmptyBorder());
      label.setOpaque(true);
      label.setBackground(Color.WHITE);
      ComponentBorder cb = new ComponentBorder(label);
      cb.setGap(0);
      cb.install(editor2);
      

参考リンク

コメント