概要

JButtonが無効な状態でのhtmlテキスト色をデフォルトのグレーではなく半透明にした元のhtmlテキスト色で上書きします。

サンプルコード

class DisabledHtmlTextLayerUI<V extends AbstractButton> extends LayerUI<V> {
  private final JLabel label = new JLabel();
  private final JPanel canvas = new JPanel();

  @Override public void updateUI(JLayer<? extends V> l) {
    super.updateUI(l);
    SwingUtilities.updateComponentTreeUI(label);
  }

  @Override public void paint(Graphics g, JComponent c) {
    super.paint(g, c);
    if (c instanceof JLayer) {
      Component view = ((JLayer<?>) c).getView();
      if (!view.isEnabled()) {
        paintDisabledText(g, view);
      }
    }
  }

  private void paintDisabledText(Graphics g, Component c) {
    if (c instanceof AbstractButton) {
      AbstractButton b = (AbstractButton) c;
      label.setFont(b.getFont());
      label.setText(b.getText());
      label.setIcon(b.getIcon());
      label.setVerticalAlignment(b.getVerticalAlignment());
      label.setHorizontalAlignment(b.getHorizontalAlignment());
      label.setVerticalTextPosition(b.getVerticalTextPosition());
      label.setHorizontalTextPosition(b.getHorizontalTextPosition());
      label.setForeground(UIManager.getColor("Button.disabledText"));
      label.setOpaque(false);
      Graphics2D g2 = (Graphics2D) g.create();
      g2.setComposite(
          AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .25f));
      Rectangle r = b.getBounds();
      SwingUtilities.paintComponent(
          g2, label, canvas, r.x, r.y, r.width, r.height);
      g2.dispose();
    }
  }
}
View in GitHub: Java, Kotlin

解説

参考リンク

コメント