概要

JSliderの目盛りに使用するJLabelを取得し、アイコンを追加したり文字色を変更するなどの変更を行います。

サンプルコード

JSlider slider = new JSlider(0, 100);
slider.setMajorTickSpacing(10);
slider.setMinorTickSpacing(5);
slider.setPaintLabels(true);
slider.setSnapToTicks(true);
slider.putClientProperty("Slider.paintThumbArrowShape", Boolean.TRUE);
Dictionary dictionary = slider.getLabelTable();
if (dictionary != null) {
  Enumeration elements = dictionary.elements();
  Icon tick = new TickIcon();
  while (elements.hasMoreElements()) {
    JLabel label = (JLabel) elements.nextElement();
    label.setBorder(BorderFactory.createEmptyBorder(1, 0, 0, 0));
    label.setIcon(tick);
    label.setIconTextGap(0);
    label.setVerticalAlignment(SwingConstants.TOP);
    label.setVerticalTextPosition(SwingConstants.BOTTOM);
    label.setHorizontalAlignment(SwingConstants.CENTER);
    label.setHorizontalTextPosition(SwingConstants.CENTER);
    label.setForeground(Color.RED);
  }
}
View in GitHub: Java, Kotlin

解説

上記のサンプルでは、JSliderのラベル(JLabel)一覧をJSlider#getLabelTable()メソッドで取得し、この各JLabelに三角形のアイコンを追加して目盛り(MajorTick)の代替としています。

  • JSlider#setOrientation(SwingConstants.VERTICAL)で作成した垂直JSliderには未対応

参考リンク

コメント