Saturday 12 January 2013

change a color panel in java

How to change a color panel in java

how to change a background color in panel java swing.



Example program:

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Color;
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener;

public class Framecolor implements ActionListener
{
        JFrame mainframe;
        JButton b1, b2, b3;
        JPanel p1;
        JLabel lb1;
        public Framecolor()
        {
                mainframe = new JFrame("Panel color change");
                b1 = new JButton("yellow");
                b2 = new JButton("blue");
                b3 = new JButton("red");
                p1 = new JPanel();
                lb1 = new JLabel("click this Button");
                p1.setLayout(null);
                b1.setBounds(10,10,80,30);
                b2.setBounds(10,60,80,30);
                b3.setBounds(10,110,80,30);
                lb1.setBounds(10,160,120,30);
                mainframe.add(p1);
                p1.add(b1);
                p1.add(b2);
                p1.add(b3);
                p1.add(lb1);
                b3.addActionListener(this);
                b2.addActionListener(this);
                b1.addActionListener(this);
                p1.setBackground(Color.gray);
                mainframe.setSize(500, 500);
                mainframe.setVisible(true);
                mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
                           
                    public void actionPerformed(ActionEvent e)
                    {
                        if(e.getSource() == b1)
                        {
                            p1.setBackground(Color.yellow);
                            lb1.setForeground(Color.red);
                        }
                       
                                           if(e.getSource() == b2)
                                        {
                                            p1.setBackground(Color.blue);
                                            lb1.setForeground(Color.yellow);
                                        }
                       
                                                    if(e.getSource() == b3)
                                                    {
                                                        p1.setBackground(Color.red);
                                                        lb1.setForeground(Color.blue);
                                                    }
                    }       
               
                    public static void main(String[] args)
                    {
                        Framecolor d = new Framecolor();
                    }
       
}       

No comments:

Post a Comment