【问题标题】:How to place an image on the screen from an event?如何从事件中将图像放置在屏幕上?
【发布时间】: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


【解决方案1】:

我实际上已经完成了与您想要实现的目标类似的事情。但是,我通过使用不同的方法来实现这一点。例如,您可以创建一个扩展 JPanel 的类 MyPanel 并覆盖 paintComponent() 方法。在 paintComponent() 方法中,您可以调用 g.drawImage(yourImage, 0, 0,null);将图像添加到您的面板。然后就是创建一个 MyPanel 实例并将其添加到 GUI 上任何您想要的位置。另外,请不要忘记在单击按钮后调用 repaint(),否则您将看不到更改。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-17
    • 2018-01-27
    相关资源
    最近更新 更多