如何通过单击 Java 中的按钮来更改图像 [英] How to change image with the click of a button in java

查看:84
本文介绍了如何通过单击 Java 中的按钮来更改图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果已经显示了图像,通过单击按钮如何将其更改为另一个?

If already an image is display, by clicking a button how can i change it to another one?

假设我缓冲了两个图像.

Say I have two image buffered.

bi = ImageIO.read(new File("1.jpg");
bi2 = ImageIO.read(new File("2.jpg"));

并显示我正在使用的 bi

and to display the bi I am using

public void paint(Graphics g){
    super.paintComponent(g);

    Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); 
    int w = ((int) dim.getWidth() / 2) - (bi.getWidth() / 2);
    int h = ((int) dim.getHeight() / 2) - (bi.getHeight() / 2);

    g.drawImage(bi, w, h, null);
}

我正在尝试这样做.

JButton b = new JButton("Change Image");
b.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent ae){
        bi = bi2;
        paint(null);
    }
});

这将 bi 设置为一个新图像并调用了 Paint() 方法,但图像查看器本身现在根本不出现.

this set bi to a new image and paint() method called, but the image viewer itself doesnt appear at all now.

继续如何设置 JFrame 背景透明但 JPanel 或 JLabel 背景不透明?

推荐答案

您需要请求repaint.

JButton b = new JButton("Change Image");
b.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent ae){
        bi = bi2;
        //invalidate();
        repaint();
    }
});

可能还需要先调用 invalidate 以允许容器被标记为由重绘管理器重绘

It may also be necessary to call invalidate first to allow the container to be marked for repainting by the repaint manager

如果您知道要绘制的区域(即旧区域和新区域),您可以调用 paintImmediately 代替

If you know the area to be painted (ie the old area and the new area) you could call paintImmediately instead

这样的东西也可以工作......

So something like this could also work...

int w = ((int) dim.getWidth() / 2) - (bi.getWidth() / 2);
int h = ((int) dim.getHeight() / 2) - (bi.getHeight() / 2);
Rectangle oldArea = new Rectangle(w, h, bi.getWidth(), bi.getHeight());

bi = bi2;
w = ((int) dim.getWidth() / 2) - (bi.getWidth() / 2);
h = ((int) dim.getHeight() / 2) - (bi.getHeight() / 2);
Rectangle newArea = new Rectangle(w, h, bi.getWidth(), bi.getHeight());

Area area = new Area();
area.add(oldArea);
area.add(newArea);

Rectangle updateArea = area.getBounds();
paintImmediately(updateArea);

这篇关于如何通过单击 Java 中的按钮来更改图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆