![](/img/trans.png)
[英]In swing GUI how to show a JPanel as maximized when the user clicks a button?
[英]I would like to open an image when a user clicks on a button in GUI
单击按钮后,我正在尝试使图像在框架中打开,到目前为止,我已将图像放入希望单击以打开的按钮中的JLabel中。 但是它立即显示出来。 关于如何设置它以便单击“剪刀”按钮后打开图像的任何想法?
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);
编辑后的代码粘贴到注释中
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);
}
}
我认为您希望在单击按钮时将JLabel(包含图像)添加到面板中。
您将必须编写以下类的代码,该类将在用户单击按钮“ 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.