我正在编写扫雷游戏,我想在点击地雷后在地雷单元格上放置椭圆形。但现在,我只想在所有单元格上放置椭圆形以进行检查。我写了下面的代码。但是当我运行该程序时,按钮上没有椭圆形。我看不出原因。如果我能得到一些建议,我将不胜感激。
public class Cell extends JButton{
...
public void painComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.orange);
g.drawOval(0,0,25,25);
}
public void draw() {
repaint();
}
...
}
public class Grid extends JPanel implements MouseListener{
...
public Grid(){
this.setLayout(new GridLayout(20,20));
cells = new Cell[20][20];
for(int i=0; i<20; i++) {
for(int j=0; j<20; j++) {
cells[i][j] = new Cell(i,j);
cells[i][j].addMouseListener(this);
cells[i][j].draw();
this.add(cells[i][j]);
}
}
plantMines();
setVisible(true);
}
...
}
最佳答案
but when I run the program there is no ovals on buttons.
public void painComponent(Graphics g) {
你打错字了。你把“paint”拼写错了。
当你重写一个方法时,你应该使用:
@Override
protected void paintComponent(Graphics g)
这样,如果您输入错误,编译器会告诉您没有重写该类的方法。
此外,不要尝试使用自定义绘画来绘制椭圆形。相反,您应该向按钮添加一个图标。然后您只需根据需要更改图标即可。
您可以轻松创建一个简单的图标来使用。以下是创建方形图标的示例:
import java.awt.*;
import javax.swing.*;
public class ColorIcon implements Icon
{
private Color color;
private int width;
private int height;
public ColorIcon(Color color, int width, int height)
{
this.color = color;
this.width = width;
this.height = height;
}
public int getIconWidth()
{
return width;
}
public int getIconHeight()
{
return height;
}
public void paintIcon(Component c, Graphics g, int x, int y)
{
g.setColor(color);
g.fillRect(x, y, width, height);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
public static void createAndShowGUI()
{
JPanel panel = new JPanel( new GridLayout(2, 2) );
for (int i = 0; i < 4; i++)
{
Icon icon = new ColorIcon(Color.RED, 50, 50);
JLabel label = new JLabel( icon );
label.setText("" + i);
label.setHorizontalTextPosition(JLabel.CENTER);
label.setVerticalTextPosition(JLabel.CENTER);
panel.add(label);
}
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(panel);
f.setSize(200, 200);
f.setLocationRelativeTo( null );
f.setVisible(true);
}
}
关于java - 在 JButton 上绘制椭圆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53473356/