Thursday 5 January 2017

Practical 7:Develop a Programe that has only one button in the frame,clicking on the button cycle through the color RED>GREEN>BLUE ans so on.One color change per Click.(Use getBackGround() method to get the current color)

Code:


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;


/**
 *
 * @author Queue
 */

public class SimpleAwt extends Frame {

    public static void main(String args[]) {

        JFrame frame = new JFrame();
        JButton button = new JButton("click");
        Container c = frame.getContentPane();
        c.setBackground(Color.WHITE);
        FlowLayout ff = new FlowLayout();
        c.setLayout(ff);

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(button);
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                changeColor(c);
            }
        });

        frame.setSize(300, 300);
        frame.setVisible(true);

    }

    public static void changeColor(Container c) {
        Color cc = c.getBackground();

        if (cc.equals(Color.WHITE)) {
            c.setBackground(Color.RED);
        } else if (cc.equals(Color.RED)) {
            c.setBackground(Color.GREEN);
        } else if (cc.equals(Color.GREEN)) {
            c.setBackground(Color.BLUE);
        } else if (cc.equals(Color.BLUE)) {
            c.setBackground(Color.WHITE);
        }

    }






Output





Thanks 

Happy Coding ;)

4 comments:

  1. Easy and Simple way::


    package pra7;
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.plaf.basic.BasicOptionPaneUI.ButtonActionListener;
    public class Pra7 extends Applet implements ActionListener{

    int CurrentColor;
    public Color[] colors=new Color[]{Color.white,Color.red,Color.blue,Color.green};
    Button b;

    public void init(){
    b = new Button("Change");
    add(b);
    b.addActionListener(this);
    setBackground(colors[0]);
    }

    @Override
    public void actionPerformed(ActionEvent arg0) {
    // TODO Auto-generated method stub
    CurrentColor++;
    if(CurrentColor == colors.length)
    {
    CurrentColor=0;
    }
    else
    {
    setBackground(colors[CurrentColor]);
    }
    }

    }


    ReplyDelete
    Replies
    1. As an Aim

      i have to use getBackGround() to get current Color

      Delete