0

I'm new in java so friends help me. i'm unable to get what i want.

ButtonFrame()
 {
  jp=new JPanel();
  btn1=new JButton("Green button");
  btn2=new JButton("Yellow button");
  add(jp);
  setTitle("change background color");
  setSize(400,300);
 }
public void actionPerformed(ActionEvent e)
{
   if(e.getSource()==btn1)
    setBackground(new Color(Color.GREEN));
   //same for others

 }
  • add an action listener to the buttons i think – james May 20 '14 at 18:40
  • 1
    Last I checked there was no `Color(Color)` constructor. Just use `setBackground(Color.GREEN)`. – Obicere May 20 '14 at 18:47
  • possible duplicate of [JPanel setBackground(Color.BLACK) does nothing](http://stackoverflow.com/questions/10148421/jpanel-setbackgroundcolor-black-does-nothing). This is about the black colour but applies to others as well. – Audrius Meškauskas May 20 '14 at 20:15

1 Answers1

1

add listener in your constructor

btn1.addActionListener(this);
btn2.addActionListener(this);

if(e.getSource()==btn1)
  setBackground(new Color(Color.GREEN));

if(e.getSource()==btn2)
  setBackground(new Color(Color.RED));   

for reference u can go to the blog http://cshotopics.blogspot.in/2014/05/how-to-apply-various-background-colors.html to know more..

Avnish Tiwary
  • 2,188
  • 22
  • 27