我想在JButton的中间绘制一个圆圈。这是我尝试过的:

JButton jButton = new JButton(new CircleIcon());

public class CircleIcon implements Icon{
    @Override
    public void paintIcon(Component c, Graphics g, int x, int y) {
        g.drawOval(10, 10, 20, 20);
    }

    @Override
    public int getIconWidth() {
        return 10;
    }

    @Override
    public int getIconHeight() {
        return 10;
    }
}


我懂了:

java - 在JButton的中心画一个圆-LMLPHP

但是我需要这样的东西:

java - 在JButton的中心画一个圆-LMLPHP

我的问题是第一张图片上的按钮中间的方形是什么?以及如何使它像第二个一样?

最佳答案

有关如何使用图标的Swing教程应该会有所帮助:Creating a Custom Icon Implementation

import java.awt.*;
import javax.swing.*;
public class CircleIconTest {
  public JComponent makeUI() {
    JPanel p = new JPanel();
    p.add(new JButton(new CircleIcon()));
    return p;
  }
  public static void main(String... args) {
    EventQueue.invokeLater(() -> {
      JFrame f = new JFrame();
      f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
      f.getContentPane().add(new CircleIconTest().makeUI());
      f.setSize(320, 240);
      f.setLocationRelativeTo(null);
      f.setVisible(true);
    });
  }
}
class CircleIcon implements Icon {
  @Override
  public void paintIcon(Component c, Graphics g, int x, int y) {
    //g.drawOval(10, 10, 20, 20);
    Graphics2D g2 = (Graphics2D) g.create();
    //Draw the icon at the specified x, y location:
    g2.drawOval(x, y, getIconWidth() - 1, getIconHeight() - 1);
    //or
    //g2.translate(x, y);
    //g2.drawOval(0, 0, getIconWidth() - 1, getIconHeight() - 1);
    g2.dispose();
  }

  @Override
  public int getIconWidth() {
    return 20;
  }

  @Override
  public int getIconHeight() {
    return 20;
  }
}

10-08 19:28