.drawLine() issues and buffered image

前端 未结 3 828
时光取名叫无心
时光取名叫无心 2020-12-11 10:11

I have a paint programme and i have all the buttons and sliders done however i am having a problem with the actual painting itself. When I drag the cursor across the scre

3条回答
  •  眼角桃花
    2020-12-11 10:55

    If I'm understanding your problem correctly, the major issue you are going to have is the number of updates you will receive when the mouse is dragged.

    Even if you drag slowly, you will not always be notified of EVERY pixel movement, instead the system waits for a "idle" state (or threshold) to notify you so it "appears" to be a smooth movement.

    I was able to put this together by modifying your code slightly

    Hello ;)

    private MouseAdapter mouseListener =
        new MouseAdapter() {
            private boolean paint = false;
            @Override
            public void mousePressed(MouseEvent me) {
    
                xClicked = me.getX();
                yClicked = me.getY();
                xDragged = xClicked;
                yDragged = yClicked;
    
                paint = true;
    
            }
    
            @Override
            public void mouseReleased(MouseEvent e) {
    
                xClicked = -1;
                xClicked = -1;
                xDragged = -1;
                yDragged = -1;
    
                paint = false;
    
            }
    
            @Override
            public void mouseMoved(MouseEvent me) {
            }
    
            @Override
            public void mouseDragged(MouseEvent me) {
    
                if (paint) {
    
                    xClicked = xDragged;
                    yClicked = yDragged;
    
                    xDragged = me.getX();
                    yDragged = me.getY();
    
                    xDragged = me.getX();
                    yDragged = me.getY();
    
                    Graphics2D g2 = bImage.createGraphics();
                    g2.setColor(Color.WHITE);
                    g2.drawLine(xClicked, yClicked, xDragged, yDragged);
                    g2.dispose();
                    imageLabel.setIcon(new ImageIcon(bImage));
    
                    me.getComponent().invalidate();
                    me.getComponent().repaint();
    
                }
    
            }
        };
    

    Basically, the idea is to draw a line from the last "known location" to the current location.

    Hope this is in the ball park

提交回复
热议问题