简体   繁体   中英

i want to change jpanel background color by clicking on buttons

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 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..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM