[英]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. 单击按钮后,我正在尝试使图像在框架中打开,到目前为止,我已将图像放入希望单击以打开的按钮中的JLabel中。 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. 我认为您希望在单击按钮时将JLabel(包含图像)添加到面板中。
You will have to code the below class which will handle the event when user clicks button 'btnPlaySci'. 您将必须编写以下类的代码,该类将在用户单击按钮“ 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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.