Java新手求助:如何生成JPanel的随机序列?
Hey there! As a fellow Java developer who started out with similar Swing questions, I've got you covered. Let's walk through how to create those 10 named JPanels and shuffle their order randomly—super straightforward once you know the steps!
First, we'll create each JPanel (labeled P1 to P10) and store them in an ArrayList—this makes it easy to shuffle later. We'll add a JLabel to each panel so you can see which one is which after shuffling.
Java's built-in Collections.shuffle() method does all the heavy lifting for randomizing the order. No need to write your own shuffle logic!
We'll use a JFrame with a simple layout to show the shuffled panels. Using FlowLayout will let the panels wrap if the window is resized, but you can use any layout you prefer.
Complete Working Example
Here's a full code snippet you can run directly:
import javax.swing.*; import java.awt.*; import java.util.ArrayList; import java.util.Collections; public class ShuffledPanelsDemo { public static void main(String[] args) { // Run Swing code on the Event Dispatch Thread (EDT) - mandatory for Swing apps SwingUtilities.invokeLater(() -> { // Create the main frame JFrame frame = new JFrame("Shuffled P1-P10 Panels"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(600, 400); frame.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10)); // Step 1: Create and store the 10 JPanels ArrayList<JPanel> panels = new ArrayList<>(); for (int i = 1; i <= 10; i++) { JPanel panel = new JPanel(); panel.setPreferredSize(new Dimension(80, 80)); panel.setBorder(BorderFactory.createLineBorder(Color.BLACK)); panel.add(new JLabel("P" + i)); // Label to identify the panel panels.add(panel); } // Step 2: Shuffle the list of panels Collections.shuffle(panels); // Step 3: Add shuffled panels to the frame for (JPanel panel : panels) { frame.add(panel); } // Make the frame visible frame.setVisible(true); }); } }
Quick Tips for Beginners
- Visual Differentiation: If you want to make each panel easier to tell apart, add a unique background color in the loop (e.g.,
panel.setBackground(new Color((int)(Math.random()*0x1000000)));). - EDT Compliance: Always run Swing code on the Event Dispatch Thread using
SwingUtilities.invokeLater()—this prevents weird UI glitches. - Re-Shuffling: Want to shuffle again? Just call
Collections.shuffle(panels)and re-add them to the frame (don't forget to callframe.revalidate()andframe.repaint()after updating the components!).
内容的提问来源于stack exchange,提问作者Dead Computer

