Reputation: 661
I am trying to write a program that draws a circle on the screen then gives you 3 buttons (red, yellow, and Green) and clicking the button changes the fill color of the circle accordingly.
I think I'm close, I just don't know how actually to create a method that will draw the circle and change the color. I can write a method to draw and fill a circle I'm just having problems merging it with jbutton
This is what i have so far:
(ignore the unused imports)
took a different approach, i don't know if it's any better. My buttons display and everything just having problems changing the color. Actually right now i cant even display a circle. i know i need to call repaint();
in my eventhandler im just not sure how to do it. This is due Sunday ive spent so many hours watching videos and reading example i just cant get mine to work. I'm sure its stupid simple but it frustrating that heck out of me!
public class test3 extends JPanel {
JRadioButton RED, YELLOW, GREEN;
Color currentColor;
public void paintComponent(Graphics g){
currentColor= Color.RED;
super.paintComponent(g);
this.setBackground(Color.WHITE);
g.setColor(currentColor);
g.fillOval(50, 50, 100, 100);
}
public static void main(String[] args) {
test3 frame = new test3();
frame.setSize(500,500);
frame.setVisible(true);
}
public test3 (){
JPanel jpRadioButtons=new JPanel();
jpRadioButtons.setLayout(new GridLayout(1,1));
jpRadioButtons.add(RED=new JRadioButton("RED"));
jpRadioButtons.add(GREEN=new JRadioButton("GREEN"));
jpRadioButtons.add(YELLOW=new JRadioButton("YELLOW"));
add(jpRadioButtons, BorderLayout.SOUTH);
ButtonGroup group=new ButtonGroup();
group.add(RED);
group.add(YELLOW);
group.add(GREEN);
GREEN.addActionListener(new ActionListener()
{
public void actionPerormed(ActionEvent e)
{
currentColor = Color.GREEN;
repaint();
}
});
}
}
Upvotes: 0
Views: 1227
Reputation: 1851
paintComponent()
method and make it draw a circle in the color, which you can read from the class variable.Your paintComponent(Graphics g)
might look something like this:
@Override
void paintComponent(Graphics g)
{
g.setColor(currentColor);
g.drawOval(50,50,100,100);
}
Upvotes: 1