gpt4 book ai didi

java - 在Java中将点击的像素颜色更改为红色?

转载 作者:行者123 更新时间:2023-11-30 02:02:15 29 4
gpt4 key购买 nike

当我单击图像的某个像素时,我希望将该像素更改为红色。我对 Java 图形没有太多经验,所以我可能错过了一些重要的东西。感谢您提供的任何帮助。

public class Main {
static BufferedImage image;

public static void main(String[] args) {
try {
image = ImageIO.read(new File("pic.png"));
} catch (IOException e) {
e.printStackTrace();
}

JFrame frame = new JFrame();
frame.getContentPane().setLayout(new FlowLayout());
JLabel label = new JLabel(new ImageIcon(image));

// change the pixels to random colors when hovering over them

label.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
System.out.println("CLICKED: " + "(" + e.getX() + "," + e.getY() + ")");
//getColorOfPixel(e.getX(), e.getY());
changeColorOfPixel(e.getX(), e.getY());
}
});

frame.getContentPane().add(label);
frame.pack();
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.setVisible(true);
}

public static void changeColorOfPixel(int xCoordinateClicked, int yCoordinateClicked) {

int width = image.getWidth();
int height = image.getHeight();

int[][] pixels = new int[width][height];

for(int i = 0; i < width; i++) {
for(int j = 0; j < height; j++) {
pixels[i][j] = image.getRGB(xCoordinateClicked, yCoordinateClicked);

if(i == xCoordinateClicked && j == yCoordinateClicked) {

Color newColor = Color.RED;

image.setRGB(xCoordinateClicked, yCoordinateClicked, newColor.getRGB());
}
}
}
}
}

最佳答案

您需要在像素颜色更改后调用frame.repaint();,因此例如只需更改 MouseAdapter 定义,如下所示(假设 frame 也将定义为 static:

    label.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);

System.out.println("CLICKED: " + "(" + e.getX() + "," + e.getY() + ")");
image.setRGB(e.getX(), e.getY(), Color.RED.getRGB());
frame.repaint();
}
});

关于java - 在Java中将点击的像素颜色更改为红色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52462010/

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