當(dāng)我單擊圖像的像素時(shí),我希望將該像素更改為紅色。我對 Java 中的圖形沒有太多經(jīng)驗(yàn),所以我可能會(huì)遺漏一些必不可少的東西。感謝您提供的任何幫助。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 回答

LEATH
TA貢獻(xiàn)1936條經(jīng)驗(yàn) 獲得超7個(gè)贊
您需要frame.repaint();在像素顏色更改后調(diào)用,因此例如只需更改這樣的MouseAdapter定義(假設(shè)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();
}
});
添加回答
舉報(bào)
0/150
提交
取消