How to draw on top of an image in Java?

后端 未结 3 1371
既然无缘
既然无缘 2021-01-16 16:39

I used JFrame to import and display an image, and used mousemotionlistener to detect the mouse clicks, and I want to be able to draw on top of the image. I want to be able t

3条回答
  •  难免孤独
    2021-01-16 16:41

    The simplest method would be to have a list of points that represent the pixels you wish to colour. Then override the paint method for the label to first call super.paint (to display the image) and then paint the pixels that have been clicked.

    List points = new ArrayList<>();
    
    myLabel = new JLabel() {
        @Override
        public void paint(Graphics g) {
            super.paint(g);
            points.forEach(p -> g.fillRect(p.x, p.y, 1, 1));
        }
    };
    

    In your mouse handling just add the current point to the list and repaint the label.

    public void mouseClicked(MouseEvent me) {
        points.add(me.getPoint());
        myLabel.repaint();
    }
    

    There are more sophisticated methods that involve buffered images but this is likely good enough to get you started.

提交回复
热议问题