gpt4 book ai didi

java - 为什么我的缓冲图像不显示在我的 JPanel 中?

转载 作者:行者123 更新时间:2023-11-29 04:53:55 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com