我有一个JButton
的网格布局,我希望在点击时用彩色圆圈填充每个按钮。我只知道如何在点击时用文本填充JButton
,我该怎么做呢?
以下是我的代码,点击后,而不是使用setText("")
我想用圆圈填充该按钮。
public void actionPerformed(ActionEvent e) {
for(int r = 0; r < row; r++){
for(int c = 0; c < col; c++){
if (board[row][col] == e.getSource()){
int temp = game.dropDiskAt(c);
game.dropDiskAt(c);
board[temp][c].setText("");
}
答案 0 :(得分:2)
这可能是一个解决方案
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.RenderingHints;
import javax.swing.Icon;
public class ColorIconRound implements Icon {
private int size;
private Paint color;
public ColorIconRound(int size, Paint color) {
this.size = size;
this.color = color;
}
@Override
public void paintIcon(Component c, Graphics g, int x, int y) {
Graphics2D g2d = (Graphics2D) g;
Paint op = g2d.getPaint();
g2d.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setPaint(color);
g2d.fillOval(x, y, size, size);
g2d.setPaint(op);
}
@Override
public int getIconWidth() {
return size;
}
@Override
public int getIconHeight() {
return size;
}
}
然后只需设置按钮的图标:
board[temp][c].setIcon(new ColorIconRound(12,Color.WHITE));
如果您不喜欢填写,请将paintIcon metod中的g2d.fillOval
更改为drawOval
。