Reputation: 490
I'm making a game for class and for this game I have an array of JButtons that need to be able to change colors based on certain factors. I had this all worked out and was changing the color with setBackground(Color) but now I am trying to change the shapes of Buttons and still be able to change the colors. My current code is:
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);
}
}
When I change my other code to use this instead of JButton, it works and I start with an 8x8 grid of pink circles which is what I want. But now I am unable to change colors. I've tried adding the changeColor method as I showed above but I get a nullPointerException when it hits line 20 (g.setColor(Color.blue)). I think the problem is with how I'm using Graphics but I can't pinpoint the specific solution. Does anyone have any suggestions?
Upvotes: 3
Views: 2991
Reputation: 39164
The only method supposed to be called to paint your custom component is paintComponent().
Inside that methods you are always setting pink color, and this one problem.
The other issue is that you are trying to paint your component inside the changeColor method. This is wrong. Let that function only change a variable that indicates the color.
I guess you are looking for something like this:
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();
}
}
Upvotes: 3