Magnus. B
Magnus. B

Reputation: 101

How to change images with a JButton

How can I change between the pictures with help of clicking the button. I made a x variable because then I could make different if-statements but that didn't work for me, probably because I did something wrong... Here is my code so far:

public class Main extends JFrame{

    private JButton changePic;
    private JPanel panel;
    private JLabel pic1;
    private JLabel pic2;
    private JLabel pic3;
    private JLabel picture;
    private int x = 0;

    public Main(){

        panel = new JPanel();
        add(panel);

        changePic = new JButton("Change Button");
        panel.add(changePic);


        pic1 = new JLabel(new ImageIcon("pic1.png"));
        pic2 = new JLabel(new ImageIcon("pic.png"));
        pic3 = new JLabel(new ImageIcon("pic3.png"));

        panel.add(pic1);
        panel.add(pic2);
        panel.add(pic3);

        changePic.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e){
                if(e.getSource() == changePic){

                }
            }
        });
        getContentPane().setBackground(Color.white);
        setSize(300, 300);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

    }

    public static void main(String[] args){
        Main fr = new Main();
    }
}

Upvotes: 0

Views: 625

Answers (1)

didxga
didxga

Reputation: 6125

public class Main extends JFrame{

    private JButton changePic;
    private JPanel panel;

    private JLabel pic1;
    private int x = 0;

    public Main(){

        panel = new JPanel();
        add(panel);

        changePic = new JButton("Change Button");
        panel.add(changePic);


        pic1 = new JLabel();
        panel.add(pic1);
        ImageIcon icon1 = new ImageIcon("pic1.gif");
        ImageIcon icon2 = new ImageIcon("pic2.gif");
        ImageIcon icon3 = new ImageIcon("pic3.gif");

        changePic.addActionListener(new ActionListener(){

            public void actionPerformed(ActionEvent e){
                if(e.getSource() == changePic){
                    if(x == 0){
                        pic1.setIcon(icon1);
                    }else if(x == 1){
                        pic1.setIcon(icon2);
                    }else if(x == 2){
                        pic1.setIcon(icon3);
                    }
                    Main.this.pack();
                    x++;
                    if(x > 2) x = 0;

                }
            }
        });
        getContentPane().setBackground(Color.white);
        setSize(300, 300);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

    }

    public static void main(String[] args){
        Main fr = new Main();
    }
}
  • you don't need multiple JLabels, use 3 ImageIcons instead.
  • you need to call JFrame's pack() every time you had UI Changes (in this case, changing image)

Upvotes: 1

Related Questions