How to change image with the click of a button in java

可紊 提交于 2019-12-13 07:52:58

问题


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"));

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);
}

I am tried to do this.

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

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

continuation of how to set JFrame background transparent but JPanel or JLabel Background opaque?


回答1:


You need to request a repaint.

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

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

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);


来源:https://stackoverflow.com/questions/12084631/how-to-change-image-with-the-click-of-a-button-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!