简体   繁体   中英

I would like to open an image when a user clicks on a button in GUI

I am trying to get an image to open within my frame once a button has been clicked, so far I have put the image in a JLabel within the button I want it to open to once clicked. But it shows up straight away. Any ideas on how to set it so that the image opens once the "scissors" button has been clicked?

    btnPlaySci = new JButton ("Scissors!");
    btnPlaySci.setBounds(180, 40, 110, 20);
    btnPlaySci.addActionListener(new PlaySciHandler());
    panel.add (btnPlaySci);
    btnPlaySci.setForeground(Color.MAGENTA);

    //below is my image, and above is the button I want it to open to

    ImageIcon rock1 = new ImageIcon("rock.jpg");
    JLabel picture = new JLabel(rock1);
    picture.setBounds(60, 200, 400, 400);
    panel.add(picture);

Edited code pasted in comment

class PlaySciHandler implements ActionListener {
        public void actionPerformed(ActionEvent event) {
            String computerRand = sps.computerChoice(); 
            txtComputerRand.setText(computerRand); 
            String result = sps.play(Sps.SCISSORS); 
            txtResult.setText(result); 
            ImageIcon rock1 = new ImageIcon("rock.jpg"); 
            JLabel picture = new JLabel(rock1); 
            picture.setBounds(60, 200, 400, 400); panel.add(picture); 
        }
    }

I think you want to add the JLabel (containing image) to panel when button is clciked.

You will have to code the below class which will handle the event when user clicks button 'btnPlaySci'.

btnPlaySci.addActionListener(new PlaySciHandler(panel)); //replace your addActionListener line with this code.

import java.awt.event.*;
class PlaySciHandler implements ActionListener 
{
    JPanel panel;
    PlaySciHandler(JPanel p)
    {
         panel = p;
    }
    public void actionPerformed(ActionEvent ae)   
    {
      ImageIcon rock1 = new ImageIcon("rock.jpg");
      JLabel picture = new JLabel(rock1);
      picture.setBounds(60, 200, 400, 400);
      panel.add(picture);   
    } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM