This is what my task is.
I have to generate 4 random cards. After which, when pressing the Refresh button, the cards should randomize again. I have implemented the repaint() method like so but it does not change how the cards appear.
public class FourCards extends JFrame {
JLabel slot1 = new JLabel(getImage());
JLabel slot2 = new JLabel(getImage());
JLabel slot3 = new JLabel(getImage());
JLabel slot4 = new JLabel(getImage());
public FourCards() {
JPanel CardsPanel = new JPanel(new GridLayout(1,4,5,5));
add(CardsPanel);
CardsPanel.add(slot1);
CardsPanel.add(slot2);
CardsPanel.add(slot3);
CardsPanel.add(slot4);
JButton jbtRefresh = new JButton("Refresh");
JPanel ButtonPanel = new JPanel();
this.add(ButtonPanel, BorderLayout.SOUTH);
ButtonPanel.add(jbtRefresh);
jbtRefresh.addActionListener(new ButtonListener());
}
public ImageIcon getImage() {
ImageIcon temp = new ImageIcon("C:/resized/" + (int)(Math.random() * 52) + ".png");
return temp;
}
public void update() {
slot1 = new JLabel(getImage());
slot2 = new JLabel(getImage());
slot3 = new JLabel(getImage());
slot4 = new JLabel(getImage());
}
public static void main(String[] args) {
FourCards frame = new FourCards();
frame.setTitle("Random 4 cards");
frame.setSize(600,280);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
class ButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
update(); // get new images
repaint();
}
}
}
In your update()
method you are creating new JLabel
objects and those objects are not added to the panel so they won't be displayed. To change the images use the setIcon(...)
method on all JLabel
s instead of creating new objects.