在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());

            }

        }

    }

}

}


尚方宝剑之说
浏览 226回答 1
1回答

LEATH

您需要frame.repaint();在像素颜色更改后调用,因此例如只需更改这样的MouseAdapter定义(假设frame也将定义为static:&nbsp; &nbsp; label.addMouseListener(new MouseAdapter() {&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public void mouseClicked(MouseEvent e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; super.mouseClicked(e);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("CLICKED: " + "(" + e.getX() + "," + e.getY() + ")");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; image.setRGB(e.getX(), e.getY(), Color.RED.getRGB());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; frame.repaint();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java