在 JButton 的中心画一个圆圈

Painting a circle at the center of JButton

我想在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;
    }
}

我知道了:

但我需要这样的东西:

我的问题是第一张图片中按钮中间的方块是什么?和第二个一样怎么做?

what is the quare in the middle of the button on the first picture?

您可能在代码上画了一个矩形。您应该只在代码块上寻找 drawRectangle( 代码行。

how to make it as in the second one?

有两种可能的解决方案。

1 - 您可以为按钮设置一些大小。因为它似乎需要变大才能像后一张图那样被看到。试试这个

jButton.setPreferredSize(new Dimension(40, 40));

2 - 您正在使用静态值绘制圆。我会为它使用动态值。像这样。

             JButton JButton = new JButton() {
                @Override
                protected void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    int nGap = 10;
                    int nXPosition = nGap;
                    int nYPosition = nGap;
                    int nWidth = getWidth() - nGap * 2;
                    int nHeight = getHeight() - nGap * 2;

                    g.setColor(Color.RED);
                    g.drawOval(nXPosition, nYPosition, nWidth, nHeight);
                    g.fillOval(nXPosition, nYPosition, nWidth, nHeight);

                }
            };

            JButton.setHorizontalAlignment(JLabel.CENTER);
            JButton.setVerticalAlignment(JLabel.CENTER);

这是不同尺寸的按钮显示。

关于如何使用图标的 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;
  }
}
jButton.setFocusPainted(false); // This will prevent the square highlight on focus!