我正在尝试编辑新的缓冲图像的像素,但是当我将构造函数用于新的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内编辑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();
            }
        });
    }
}

关于java - 为什么我的缓冲图像不显示在我的JPanel中?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34444986/

10-09 18:09