Untitled
unknown
plain_text
5 months ago
1.8 kB
4
Indexable
Here's a simple Java Swing example that creates a button. When clicked, it shows a white box with a 25% chance of it being black instead. ```java import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Random; public class ColorBoxExample { public static void main(String[] args) { JFrame frame = new JFrame("Color Box Example"); JButton button = new JButton("Click Me"); button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Random random = new Random(); Color boxColor = random.nextInt(4) == 0 ? Color.BLACK : Color.WHITE; // 25% chance for black showColorBox(boxColor); } }); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(300, 200); frame.setLayout(new FlowLayout()); frame.add(button); frame.setVisible(true); } private static void showColorBox(Color color) { JFrame boxFrame = new JFrame(); boxFrame.setSize(100, 100); boxFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); boxFrame.getContentPane().setBackground(color); boxFrame.setVisible(true); } } ``` ### Explanation: 1. **JFrame**: The main window. 2. **JButton**: A button that triggers the action. 3. **ActionListener**: An event handler for button clicks. 4. **Random**: Used to generate a random number for determining the color. 5. **showColorBox**: A method that creates a new window with the chosen color. You can run this code in any Java development environment. When you click the button, it will pop up a box that is either white or black based on the specified probability.
Editor is loading...
Leave a Comment