gpt4 book ai didi

java - 在 JButton 的中心画一个圆

转载 作者:行者123 更新时间:2023-12-01 06:49:56 25 4
gpt4 key购买 nike

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

我得到了这个:

enter image description here

但我需要这样的东西:

enter image description here

我的问题是第一张图片上按钮中间的方 block 是什么?那么如何才能像第二个一样呢?

最佳答案

有关如何使用图标的 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;
}
}

关于java - 在 JButton 的中心画一个圆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37371596/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com