Note that there are some explanatory texts on larger screens.

plurals
  1. PODisplay cards of CardLayout in random order?
    primarykey
    data
    text
    <p>I want to have a random order for displaying the cards or screens in my CardLayout. I need guidance on how to accomplish this. What is strategy I should use? </p> <p>I tried using the code below, but it is in a fixed order. I want to be able to choose whichever order I like.</p> <p><strong>EDIT !</strong></p> <p>Sorry, by random order I did not mean shuffling. But, it is good to know. I want the user of the program to be able to enter some input. Depending on the value of the input, a particular screen/card is displayed.</p> <pre><code>import java.awt.*; import javax.swing.*; import java.awt.event.*; public class CardLayoutExample extends JFrame { private int currentCard = 1; private JPanel cardPanel; private CardLayout cl; public CardLayoutExample() { setTitle("Card Layout Example"); setSize(300, 150); cardPanel = new JPanel(); cl = new CardLayout(); cardPanel.setLayout(cl); JPanel p1 = new JPanel(); JPanel p2 = new JPanel(); JPanel p3 = new JPanel(); JPanel p4 = new JPanel(); JLabel lab1 = new JLabel("Card1"); JLabel lab2 = new JLabel("Card2"); JLabel lab3 = new JLabel("Card3"); JLabel lab4 = new JLabel("Card4"); p1.add(lab1); p2.add(lab2); p3.add(lab3); p4.add(lab4); cardPanel.add(p1, "1"); cardPanel.add(p2, "2"); cardPanel.add(p3, "3"); cardPanel.add(p4, "4"); JPanel buttonPanel = new JPanel(); JButton b1 = new JButton("Previous"); JButton b2 = new JButton("Next"); buttonPanel.add(b1); buttonPanel.add(b2); b1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (currentCard &gt; 1) { currentCard -= 1; cl.show(cardPanel, "" + (currentCard)); } } }); b2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if (currentCard &lt; 4) { currentCard += 1; cl.show(cardPanel, "" + (currentCard)); } } }); getContentPane().add(cardPanel, BorderLayout.NORTH); getContentPane().add(buttonPanel, BorderLayout.SOUTH); } public static void main(String[] args) { CardLayoutExample cl = new CardLayoutExample(); cl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); cl.setVisible(true); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload