Advertisement
zoro-10

ChangeColor.java

Mar 30th, 2024 (edited)
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.21 KB | None | 0 0
  1. import java.awt.*;
  2. import java.awt.event.ActionEvent;
  3. import java.awt.event.ActionListener;
  4. import java.util.Random;
  5. import javax.swing.*;
  6.  
  7. public class ChangeColor extends JFrame {
  8.  
  9.   private JPanel colorPanel;
  10.   private JButton changeColorButton;
  11.  
  12.   public ChangeColor() {
  13.     setTitle("Random Color Changer");
  14.     setSize(300, 200);
  15.     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  16.     setLayout(new BorderLayout());
  17.     colorPanel = new JPanel();
  18.     changeColorButton = new JButton("Change Color");
  19.     add(colorPanel, BorderLayout.CENTER);
  20.     add(changeColorButton, BorderLayout.SOUTH);
  21.     changeColorButton.addActionListener(
  22.       new ActionListener() {
  23.         @Override
  24.         public void actionPerformed(ActionEvent e) {
  25.           ColorChanger();
  26.         }
  27.       }
  28.     );
  29.   }
  30.  
  31.   private void ColorChanger() {
  32.     Random random = new Random();
  33.     Color randomColor = new Color(
  34.       random.nextInt(256),
  35.       random.nextInt(256),
  36.       random.nextInt(256)
  37.     );
  38.     colorPanel.setBackground(randomColor);
  39.   }
  40.  
  41.   public static void main(String args[]) {
  42.     SwingUtilities.invokeLater(() -> {
  43.       ChangeColor app = new ChangeColor();
  44.       app.setVisible(true);
  45.     });
  46.   }
  47. }
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement