Programming Blog

This blog is about technical and programming questions and there solutions. I also cover programs that were asked in various interviews, it will help you to crack the coding round of various interviews

Friday, 22 December 2017

Java program to create button

import java.awt.*;

import java.awt.event.*;



public class Button extends Frame implements ActionListener

{

  Button rb, gb, bb; // create 3 button var

  public ButtonDemo()            
  {

    FlowLayout fl = new FlowLayout();    // choose any layout i choose flow layout

    setLayout(fl);



    rb = new Button("Red");. // map variables to objects

    gb = new Button("Green");

    bb = new Button("Blue");



    rb.addActionListener(this);   // link the listener with the button

    gb.addActionListener(this);

    bb.addActionListener(this);



    add(rb);            // add button to frame

    add(gb);

    add(bb);   



    setTitle("Buttons Created");

    setSize(300, 350);                      // size of frame

    setVisible(true);    // to make frame visible on screen

  }

                   // override the only abstract method of ActionListener interface

  public void actionPerformed(ActionEvent e)

  {

    String str = e.getActionCommand();    // to know which Java button user clicked

    System.out.println("You clicked " + str + " button");  // just beginner's interest



    if(str.equals("Red"))

    {

      setBackground(Color.red);

    }

    else if(str.equals("Green"))

    {

      setBackground(Color.green);

    }

    else if(str.equals("Blue"))

    {

      setBackground(Color.blue);

    }

  }

  public static void main(String args[])

  {

    new ButtonDemo();                       // anonymous object of ButtonDemo just to call the constructor

  }                    // as all the code is in the constructor

}

No comments:

Post a Comment