簡體   English   中英

為什么我的緩沖圖像不會顯示在我的JPanel中?

[英]Why does my buffered image not display in my JPanel?

我正在嘗試編輯新緩沖圖像的像素,但是當我使用構造函數進行新的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();
            }
        });
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM