在 Java 中单击按钮时更改 jframe 上的图像 [英] Change Images on jframe when a button is clicked in Java

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

问题描述

我一直试图弄清楚为什么单击按钮后下一张图片没有显示在同一面板上.我想将这些类分开而不是一个类,并使用 repaint() 用新图片重新调用paintComponent().

I have been trying to figure this out why not the next picture showing on the same panel after click the button. I want to separate those classes not into one class and used repaint() to re-invoke paintComponent() with the new pic.

请帮帮我.我快要死了:(

Please help me. I am almost dying :(

  • 当我运行它时,第一张图片看起来很好.当单击按钮将第一张图片更改为第二张图片时,面板只会继续显示第一张图片.

谢谢.

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.*;

class drawImage extends JPanel {

    BufferedImage[] b = new BufferedImage[2];

    public drawImage() {
        try {
            b[0] = ImageIO.read(new File("img/gameOn.png"));
            b[1] = ImageIO.read(new File("img/gameOff.png"));
        } catch (IOException e) {

            e.printStackTrace();
        }

    }

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

        g.drawImage(b[0], 0, 0, null);

    }

    public void setNextImage(BufferedImage image) {

        b[0] = image;

        repaint();
    }

    public BufferedImage getB0() {
        return b[0];
    }

    public BufferedImage getB1() {
        return b[1];
    }

}// end drawImage

class clickedListener implements ActionListener {

    BufferedImage pre = new drawImage().getB0();
    BufferedImage next = new drawImage().getB1();

    @Override
    public void actionPerformed(ActionEvent e) {

        new drawImage().setNextImage(next);

    }

}

public class buttonFrame {
    public static void main(String[] args) throws IOException {
        JFrame jf = new JFrame("Button & Frame");
        JButton btn = new JButton("Click");

        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.setVisible(true);
        jf.setLayout(new GridLayout(2, 0));
        jf.add(new drawImage());
        jf.add(btn);
        jf.setSize(200, 250);

        btn.addActionListener(new clickedListener());

    }

}

推荐答案

为什么不改变您的方法并改用 JLabel?将您的图像设置为标签上的图标并将其添加到您的 JPanel:

Why not change your approach and make use of a JLabel instead? Set your image as an icon on the label and add it to your JPanel:

BufferedImage image = ImageIO.read(new File("image-path"));
JLabel label = new JLabel(new ImageIcon(image));
panel.add(label);

然后,您可以在每次想要更改图像时对 JLabel#setIcon(...) 进行后续调用.

You can then make subsequent calls to JLabel#setIcon(...) each time you want the image to change.

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

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