Reputation: 63
I want to repaint a circle whenever a button is pressed.
Currently, I have it whenever I press a button, it prints to the console what button I pressed. For example, if I press the "Paint Red" button, I want it to fill the circle with red, and the same with the other colors as well. I'm trying to wrap my head around the whole paint/paintComponent difference.
This is what I have so far...
public class testCircle extends JPanel {
public void paint(Graphics g)
{
setSize(500,500);
int R = (int) (Math.random( )*256);
int G = (int)(Math.random( )*256);
int B= (int)(Math.random( )*256);
Color randomColor = new Color(R, G, B);
g.setColor(randomColor);
g.drawOval(75, 100, 200,200);
g.fillOval(75, 100, 200, 200);
}
public static void main(String[] args)
{
JFrame frame = new JFrame();
frame.setSize(400, 400);
testCircle circlePanel = new testCircle();
frame.add(circlePanel);
JButton redButton = new JButton("Paint Red");
redButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event)
{
System.out.println("Red Button Pressed!");
}
});
JButton blueButton = new JButton("Paint Blue");
blueButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event)
{
System.out.println("Blue Button Pressed!");
}
});
JButton greenButton = new JButton("Paint Green");
greenButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event)
{
System.out.println("Green Button Pressed!");
}
});
redButton.setPreferredSize(new Dimension(100,100));
blueButton.setPreferredSize(new Dimension(100,100));
greenButton.setPreferredSize(new Dimension(100,100));
frame.setLayout(new FlowLayout());
frame.add(redButton);
frame.add(blueButton);
frame.add(greenButton);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Upvotes: 0
Views: 470
Reputation: 205875
Consider these changes to your code:
As discussed here, Swing programs should override paintComponent()
instead of overriding paint()
.
Give your panel an attribute for currentColor
.
private Color currentColor;
Let each button's ActionListener
set currentColor
and invoke repaint()
.
currentColor = color;
repaint();
Use Action
for to encapsulate your program's functionality.
A complete example is examined here.
Upvotes: 3
Reputation: 24640
You don't trigger a "repaint" anywhere in your code. That should work:
redButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
System.out.println("Red Button Pressed!");
frame.invalidate();
frame.validate();
}
});
Upvotes: 0