Java 我想在用户单击GUI中的按钮时打开一个图像
我试图在点击按钮后在我的框架内打开一个图像,到目前为止,我已经将图像放在一个JLabel中,我希望在点击按钮后将其打开。但它马上就出现了。关于如何设置它,使图像在单击“剪刀”按钮后打开,有什么想法吗Java 我想在用户单击GUI中的按钮时打开一个图像,java,image,swing,user-interface,jbutton,Java,Image,Swing,User Interface,Jbutton,我试图在点击按钮后在我的框架内打开一个图像,到目前为止,我已经将图像放在一个JLabel中,我希望在点击按钮后将其打开。但它马上就出现了。关于如何设置它,使图像在单击“剪刀”按钮后打开,有什么想法吗 btnPlaySci = new JButton ("Scissors!"); btnPlaySci.setBounds(180, 40, 110, 20); btnPlaySci.addActionListener(new PlaySciHandler()); pa
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);
}
}
PlaySciHandler类的代码?类PlaySciHandler实现ActionListener{public void actionPerformed(ActionEvent事件){String computerRand=sps.computerChoice();txtcomuterrand.setText(computerRand);String result=sps.play(sps.SCISSORS);txtreult.setText(result);ImageIcon rock1=新ImageIcon(“rock.jpg”);JLabel picture=new JLabel(rock1);picture.setBounds(60,200,400,400);panel.add(picture);}}很抱歉,之前我的回答不正确,但现在它可以执行您需要的操作。从将image设置为label的主类中删除代码。点击按钮,这样图像就可以被看到。我试着把它放到我的动作监听器中,放在我已经有的上面,但它没有出现?类PlaySciHandler实现ActionListener{public void actionPerformed(ActionEvent事件){String computerRand=sps.computerChoice();txtcuterrand.setText(computerRand);String result=sps.play(sps.SCISSORS);txtreult.setText(result);ImageIcon rock1=new ImageIcon(“rock.jpg”);JLabel picture=new JLabel(rock1);picture.setBounds(60200400400);panel.add(picture);}我已经更新了答案,现在它可以工作了。只需将这个新类放在现有源文件中的任何位置,或创建新的playsichandler.java文件在用户单击任何内容之前,应将
JLabel
添加到GUI中。选择图像后,调用label.setIcon(图标)
。不要对组件使用绝对边界(它们通常会被忽略),并确保在添加新组件后validate()
/repaint()
GUI。对提问者来说,这个答案可能解决了眼前的问题,但这样做会增加更多问题。