Swing aplicsn click


 Create a swing application that randomly changes color on button click.




 import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

import java.util.Random;


public class RandomColorChanger extends JFrame {

    private JPanel colorPanel;

    private JButton changeColorButton;


    public RandomColorChanger() {

        setTitle("Random Color Changer");

        setSize(300, 200);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);


        // Initialize components

        colorPanel = new JPanel();

        colorPanel.setBackground(Color.WHITE); // Initial background color is white


        changeColorButton = new JButton("Change Color");


        // Add action listener to the button

        changeColorButton.addActionListener(new ActionListener() {

            @Override

            public void actionPerformed(ActionEvent e) {

                changeColor();

            }

        });


        // Layout components

        getContentPane().setLayout(new BorderLayout());

        getContentPane().add(colorPanel, BorderLayout.CENTER);

        getContentPane().add(changeColorButton, BorderLayout.SOUTH);

    }


    private void changeColor() {

        // Generate random values for RGB

        Random random = new Random();

        int red = random.nextInt(256);

        int green = random.nextInt(256);

        int blue = random.nextInt(256);


        // Create a new Color object with the random values

        Color randomColor = new Color(red, green, blue);


        // Set the background color of the panel to the random color

        colorPanel.setBackground(randomColor);

    }


    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {

            @Override

            public void run() {

                new RandomColorChanger().setVisible(true);

            }

        });

    }

}


Comments

Popular posts from this blog

JColorchooser