改变JButton的形状

Gle*_*imo 1 java swing shape jbutton

我正在制作游戏Master Mind,我已经用JButton填充了我的矩阵,所以人们可以点击它们来改变颜色.

现在我想将矩形按钮的形状更改为圆形,是否有一种方法可以一次更改它们,因为我使用循环来创建它们.

JWi*_*ill 5

以下是一些必须覆盖以编辑组件形状的方法.(包括示例代码)

protected void paintComponent(Graphics g) 
  {
    if (getModel().isArmed()) {
      g.setColor(Color.lightGray);
    } else {
      g.setColor(getBackground());
    }
    g.fillOval(0, 0, getSize().width-1,getSize().height-1);

    super.paintComponent(g);
  }

  protected void paintBorder(Graphics g) {
    g.setColor(getForeground());
    g.drawOval(0, 0, getSize().width-1,     getSize().height-1);
  }

  Shape shape;
  public boolean contains(int x, int y) {
    if (shape == null || 
      !shape.getBounds().equals(getBounds())) {
      shape = new Ellipse2D.Float(0, 0, getWidth(), getHeight());
    }
    return shape.contains(x, y);
  }
Run Code Online (Sandbox Code Playgroud)