Java program to create frame with a button.

Below code is used to create a frame with a button:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.util.*;
    
public class ButtonFrame extends Frame implements ActionListener
{
    Button b;
    Random rand;
    Color c;
    
    public ButtonFrame() 
    {
        addWindowListener(new MyWindowAdapter());
        b=new Button("Change Color");
        b.addActionListener(this);
        add(b);
        rand=new Random();
    }
    public void paint(Graphics g) { }
    public static void main(String args[])
    {
        ButtonFrame obnew ButtonFrame();
        ob.setSize(new Dimension(300200));
        ob.setTitle("An AWT-Based Application--Buttons in frame");
        ob.setLayout(new FlowLayout());
        ob.setVisible(true);
    }
    public void actionPerformed(ActionEvent ie) {
        //repaint();
        float r=rand.nextFloat();
        float gr=rand.nextFloat();
        float b=rand.nextFloat();
        c=new Color(r,gr,b);
        setBackground(c);
    }
}
class MyWindowAdapter extends WindowAdapter 
{
    public void windowClosing(WindowEvent we)
    {
        System.exit(0);
    }
}

Thank You.

© Copyright - 2018 - 2021 | All rights reserved at Funda of Web IT