更改在Java中单击为红色的像素的颜色?

时间:2018-09-23 00:38:53

标签: java

当我单击图像的像素时,我希望将该像素更改为红色。我没有使用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());
            }
        }
    }
}
}

1 个答案:

答案 0 :(得分:2)

您需要在像素颜色更改后致电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();
        }
    });