Search code examples
javaswingjpaneljbuttonimageicon

Changing JPanel Icon when JButton is clicked


The JFrame window needs to display a random dice image. When the button is clicked, the random dice image needs to change. I have figured out how to display the random dice image, but I cannot figure out how to use the actionlistener to generate a new random dice image. I am only in my third Java class, so any guidance would be greatly appreciated!

package guiDice;

import java.awt.BorderLayout;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.Font;
import javax.swing.SwingConstants;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
import java.awt.event.ActionListener;
import java.util.Random;
import java.awt.event.ActionEvent;

public class LabGuiDice extends JFrame {

    private JPanel contentPane;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    LabGuiDice frame = new LabGuiDice();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public LabGuiDice() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));
        setContentPane(contentPane);

        JButton btnRollem = newDiceRoll();
        contentPane.add(btnRollem, BorderLayout.SOUTH);

        JLabel lblDice = newDiceImage();
        contentPane.add(lblDice, BorderLayout.CENTER);
    }

    private JLabel newDiceImage() {
        Random rnd = new Random();
        int rand1 = 0;
        rand1 = rnd.nextInt(6)+1;
        JLabel lblDice = new JLabel("");
        switch (rand1) {
        case 1:
            lblDice.setHorizontalAlignment(SwingConstants.CENTER);
            lblDice.setIcon(new ImageIcon(LabGuiDice.class.getResource("/Dice/die-1.png")));
            break;
        case 2:
            lblDice.setHorizontalAlignment(SwingConstants.CENTER);
            lblDice.setIcon(new ImageIcon(LabGuiDice.class.getResource("/Dice/die-2.png")));
            break;
        case 3:
            lblDice.setHorizontalAlignment(SwingConstants.CENTER);
            lblDice.setIcon(new ImageIcon(LabGuiDice.class.getResource("/Dice/die-3.png")));
            break;
        case 4:
            lblDice.setHorizontalAlignment(SwingConstants.CENTER);
            lblDice.setIcon(new ImageIcon(LabGuiDice.class.getResource("/Dice/die-4.png")));
            break;
        case 5:
            lblDice.setHorizontalAlignment(SwingConstants.CENTER);
            lblDice.setIcon(new ImageIcon(LabGuiDice.class.getResource("/Dice/die-5.png")));
            break;
        case 6:
            lblDice.setHorizontalAlignment(SwingConstants.CENTER);
            lblDice.setIcon(new ImageIcon(LabGuiDice.class.getResource("/Dice/die-6.png")));
            break;
        }
        return lblDice;
    }

    private JButton newDiceRoll() {
        JButton btnRollem = new JButton("Roll 'Em");
        btnRollem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {

            }
        });
        btnRollem.setBorderPainted(false);
        btnRollem.setFont(new Font("Bodoni 72 Smallcaps", Font.PLAIN, 27));
        btnRollem.setOpaque(true);
        btnRollem.setBackground(new Color(255, 0, 0));
        return btnRollem;
    }
}

Solution

  • Create a method that generates the integer and sets the icon to the label. But in order to do that, label should be a field in the class, so all methods can access it. For example:

    private void rollDice() {
        Random random = new Random();
        int randomInt = random.nextInt(6) + 1;
        String resource = String.format("/Dice/die-%d.png", randomInt);
        Icon icon = new ImageIcon(LabGuiDice.class.getResource(resource));
        diceIconLabel.setIcon(icon);
    }
    

    and then:

    btnRollem.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            rollDice();
        }
    });
    

    with full code:

    public class LabGuiDice extends JFrame {
    
        private JPanel contentPane;
        private JLabel diceIconLabel;
    
        /**
         * Launch the application.
         */
        public static void main(String[] args) {
            EventQueue.invokeLater(new Runnable() {
                @Override
                public void run() {
                    try {
                        LabGuiDice frame = new LabGuiDice();
                        frame.setVisible(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    
        /**
         * Create the frame.
         */
        public LabGuiDice() {
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setBounds(100, 100, 450, 300);
            contentPane = new JPanel();
            contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
            contentPane.setLayout(new BorderLayout(0, 0));
            setContentPane(contentPane);
    
            JButton btnRollem = newDiceRoll();
            contentPane.add(btnRollem, BorderLayout.SOUTH);
    
            diceIconLabel = newDiceImage();
            contentPane.add(diceIconLabel, BorderLayout.CENTER);
            rollDice();
            pack();
        }
    
        private void rollDice() {
            Random random = new Random();
            int randomInt = random.nextInt(6) + 1;
            String resource = String.format("/Dice/die-%d.png", randomInt);
            Icon icon = new ImageIcon(LabGuiDice.class.getResource(resource));
            diceIconLabel.setIcon(icon);
        }
    
        private JLabel newDiceImage() {
            JLabel lblDice = new JLabel("");
            lblDice.setHorizontalAlignment(SwingConstants.CENTER);
            return lblDice;
        }
    
        private JButton newDiceRoll() {
            JButton btnRollem = new JButton("Roll 'Em");
            btnRollem.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    rollDice();
                }
            });
            btnRollem.setBorderPainted(false);
            btnRollem.setFont(new Font("Bodoni 72 Smallcaps", Font.PLAIN, 27));
            btnRollem.setOpaque(true);
            btnRollem.setBackground(new Color(255, 0, 0));
            return btnRollem;
        }
    }