【问题标题】:Why does my buffered image not display in my JPanel?为什么我的缓冲图像不显示在我的 JPanel 中?
【发布时间】:2015-12-23 22:58:47
【问题描述】:

我正在尝试编辑新缓冲图像的像素,但是当我使用新 BufferedImage 的构造函数时,它不显示,当我加载图像并设置它的像素时。为什么不显示?

public void paintComponent(Graphics g) {
    super.paintComponent(g);
    int w = 1000;
    int h = 1000;

    BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
                          //ImageIO.read(new File("/Users/george/Documents/Ali.png"));

    int color = Color.BLACK.getRGB();

    for(int x = 0; x < w; x++) {
        for(int y = 0; y < h; y++) {
            image.setRGB(x, y, color);
        }
    }
    g.drawImage(image, 0, 0, null);
}

【问题讨论】:

  • 您上面的代码将运行相当长时间,因此不属于paintComponent 方法。上面应该在paintComponent 中的唯一代码是第一行和最后一行——超级调用和g.drawImage(...),仅此而已。图像创建和更改代码属于其他地方,因此它不会减慢程序的感知响应速度。也永远不要在 paintComonent 中读取图像,除非您想让用户体验痛苦的无响应 GUI。
  • 我只是想创建一个图像,想知道为什么这两种方法会产生不同的结果。
  • 无论如何——你做错了,所以你应该期待意想不到的结果。在paintComponent 中编辑图像是愚蠢的,并且有使paintComponent 不起作用的风险。首先做正确的事,例如,在别处编辑你的图像,然后如果它失败了,然后显示你更正的代码。
  • 对我来说很好,您可以考虑使用this 作为ImageObserverdrawImage,坦率地说,Graphics#fillRect 会更快:P - 但我也同意 HovercraftFullOfEels跨度>

标签: java swing jpanel bufferedimage


【解决方案1】:

同样,不要在paintComponent 中编辑BufferedImage——在别处进行。例如:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;

import javax.swing.*;

public class ImageEdit extends JPanel {
    private static final int PREF_W = 400;
    private static final int PREF_H = PREF_W;
    private static final int COLOR = Color.BLACK.getRGB();
    private BufferedImage image = null;

    public ImageEdit() {
        image = new BufferedImage(PREF_W, PREF_H, BufferedImage.TYPE_INT_RGB);
        for(int x = 0; x < PREF_H; x++) {
            for(int y = 0; y < PREF_W; y++) {
                image.setRGB(x, y, COLOR);
            }
        }        
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (image != null) {
            g.drawImage(image, 0, 0, this);
        }
    }

    @Override
    public Dimension getPreferredSize() {
        if (isPreferredSizeSet()) {
            return super.getPreferredSize();
        }
        return new Dimension(PREF_W, PREF_H);
    }

    private static void createAndShowGui() {
        ImageEdit mainPanel = new ImageEdit();

        JFrame frame = new JFrame("ImageEdit");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGui();
            }
        });
    }
}

【讨论】:

    猜你喜欢
    • 2022-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-04
    • 2013-08-21
    • 1970-01-01
    • 2014-08-26
    相关资源
    最近更新 更多