【问题标题】:Need to change the color of a JButton with a different shape需要更改具有不同形状的 JButton 的颜色
【发布时间】:2011-11-20 22:36:46
【问题描述】:

我正在为班级制作一款游戏,对于这个游戏,我有一组 JButton,它们需要能够根据某些因素改变颜色。我已经解决了这一切,并且正在使用 setBackground(Color) 更改颜色,但现在我正在尝试更改按钮的形状并且仍然能够更改颜色。 我当前的代码是:

import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class CircleButton extends JButton {

  Graphics g = this.getGraphics();

  public CircleButton(){
    super();
    setContentAreaFilled(false);
  }

  protected void paintComponent(Graphics g) {
   g.setColor(Color.pink);
   g.fillOval(0, 0, getSize().width-1, getSize().height-1);
   super.paintComponent(g);
}

  public void changeColor(Color c) {
    g.setColor(Color.blue);
    g.fillOval(0, 0, getSize().width-1, getSize().height-1);
    super.paintComponent(g);
  }                        
}

当我更改我的其他代码以使用它而不是 JButton 时,它可以工作,我从一个 8x8 的粉红色圆圈网格开始,这正是我想要的。但现在我无法改变颜色。我已经尝试添加上面显示的 changeColor 方法,但是当它到达第 20 行(g.setColor(Color.blue))时,我得到了一个 nullPointerException。 我认为问题在于我如何使用 Graphics,但我无法确定具体的解决方案。 有人有什么建议吗?

【问题讨论】:

  • noooo .... 你永远不会在 Swing 中使用 component.getGraphics!

标签: java swing colors jbutton shape


【解决方案1】:

绘制自定义组件应该调用的唯一方法是paintComponent()。

在这些方法中,您总是设置粉红色,这是一个问题。

另一个问题是您试图在 changeColor 方法中绘制组件。这是错误的。让该函数仅更改指示颜色的变量。

我猜你正在寻找这样的东西:

import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class CircleButton extends JButton {

 // Graphics g = this.getGraphics();
 Color col = Color.pink;
  public CircleButton(){
   //commented as unuseful.. super call is implicit if constructor has no arguments
   // super();
    setContentAreaFilled(false);
  }

  protected void paintComponent(Graphics g) {
   g.setColor(this.color);
   g.fillOval(0, 0, getSize().width-1, getSize().height-1);
   super.paintComponent(g);
}

  public void changeColor(Color c) {
      this.color = Color.blue; //only change the color. Let paintComponent paint
      this.repaint();
  }                        
}

【讨论】:

  • 但是我如何让它真正改变颜色。它改变了颜色变量。 “this.color”返回一个找不到变量颜色的错误,所以我尝试用 col 补充它,但所做的只是更改变量,但在我调用paintComponent 之前不会使用该变量。我不知道如何调用paintComponent,因为我不确定在参数中使用什么。编辑:没关系,修复它。颜色起作用了,我只是忘记在paintComponent中将它更改为(this.color)。非常感谢您的帮助!
  • 糟糕,以为已经完成了,但我错了。它几乎可以工作,但只有当我将鼠标悬停在圆圈上时才会更新颜色。有谁知道我改变颜色后立即更新它的方法。 @Heisenbug
  • 又一次能够修复它。只需要添加“repaint();”到我的 changeColor 方法。很确定我现在已经完成了这部分代码。再次,非常感谢。
  • 您必须在设置颜色后至少调用 repaint():底层按钮不知道该新属性。
  • @kleopatra:是的..谢谢..我忘记了重绘方法调用。刚刚修好了。
猜你喜欢
  • 2013-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-11
  • 1970-01-01
  • 2016-10-19
  • 2017-04-08
  • 2019-01-29
相关资源
最近更新 更多