[英]Adding ImageIcon to already visible GUI on button click
I'm a bit confused as to why my program isn't working. 我对为什么我的程序无法正常工作感到有些困惑。 I am trying to add a image to the frame when I click the button.
单击按钮时,我试图将图像添加到框架中。 I have verified in java that the file exists and it can find the photo.
我已在Java中验证该文件存在,并且可以找到照片。 I have also verified that the button works.
我还验证了该按钮是否有效。 But when I compile and click the button it does nothing at all...if someone could guide me in the correct direction it would be much appreciated.
但是当我编译并单击按钮时,它什么也没有做……如果有人可以正确地引导我,将不胜感激。
package gamePractice;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
public class window {
public static void main(String[] args){
JFrame frame = new JFrame("ex");
JPanel panel = new JPanel();
JButton button = new JButton();
button.setText("Press Me");
panel.add(button);
frame.add(panel);
frame.setSize(300, 300);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(e.getSource() == button) {
ImageIcon img = new ImageIcon(getClass().getResource("t.jpg"));
JLabel stickLabel = new JLabel("yes", img, SwingConstants.CENTER);
JPanel panel2 = new JPanel();
panel2.add(stickLabel);
frame.add(panel2);
}
}
});
}
}
JComponent
can be placed to CENTER
area) JComponent
放置到CENTER
区域) JPanel panel = new JPanel();
JPanel panel = new JPanel();
with JPanel panel2 = new JPanel();
JPanel panel2 = new JPanel();
, then JButton button = new JButton();
JButton button = new JButton();
can dissapears, then there are two options, note JPanel uses FlowLayout 然后有两个选项,请注意, JPanel使用FlowLayout
(correct) to add JLabel
to JPanel
, change LayoutManager
to JPanel
by using BorderLayout
, load ImageIcon
to the local variable, inside ActionListener
to call JLabel.setText()
and JLabel.setIcon()
(正确)将
JLabel
添加到JPanel
,通过使用BorderLayout
将LayoutManager
更改为JPanel
,将ImageIcon
加载到局部变量,在ActionListener
内调用JLabel.setText()
和JLabel.setIcon()
(replacing content) call revalidate();
(替换内容)调用
revalidate();
and repaint();
和
repaint();
to JFrame
, but JPanel panel = new JPanel();
到
JFrame
,但JPanel panel = new JPanel();
with JButton button = new JButton();
使用
JButton button = new JButton();
can dissapears forever, 可以永远消失
You are adding Components to an already visible container - you need to call let the LayoutManager
know about the change by calling revalidate
followed by repaint
您正在将Components添加到一个已经可见的容器中-您需要通过调用
revalidate
和repaint
来让LayoutManager
知道更改
panel2.add(stickLabel);
frame.add(panel2);
panel2.revalidate();
panel2.repaint();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.