【发布时间】:2013-11-03 20:13:00
【问题描述】:
我想在事件发生时在屏幕上添加图像。在我的情况下,这将来自一个被点击的按钮。我试图自己解决这个问题,但图像没有出现。不知道怎么回事。
我的代码:
JButton button2 = new JButton("+");
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
System.out.println("button #2 working");
label2 = new JLabel(new ImageIcon(this.getClass().getResource("50.png")));
label2.setLocation(10, 60);
label2.setSize(300, 532);
add(label2);
//? Not working
}
});
button2.setSize(50, 40);
button2.setFont(new Font("Arial", 1, 20));
button2.setLocation(110, 592);
button2.setBackground(Color.ORANGE);
content.add(button2);
【问题讨论】:
-
尝试在您有评论的地方添加
revalidate();//? Not working -
revalidate() 只处理更新布局,repaint() 另一方面处理重新绘制或刷新视图(组件)。对此进行快速类比是一个简单的 JTextField。每当您在文本字段中键入内容时,Swing 会自动为您调用 repaint() 以便刷新或重新绘制组件以查看更改(即键入的字符)
-
我想出了一个简单的解决方案。我将图像放在屏幕上,并将其设置为不可见。 image1.setVisible(false);当点击按钮时,图片会出现image1.setVisible(true);
标签: java eclipse image swing events