This question already has an answer here:
Java: mouseDragged and moving around in a graphical interface
                            
                                (1个答案)
                            
                    
                2年前关闭。
        

    

我必须画一个简单的十字准线。我所看到的只是一个空白面板。

class ChartPanel extends JPanel implements MouseMotionListener{
    Graphics2D g;
    Dimension dimFrame;
    ChartPanel() {
        addMouseMotionListener(this);
    }
    public void mouseMoved(MouseEvent e) {
        drawCrosshair(e.getX(),e.getY());
    }
    public void mouseDragged(MouseEvent e) {}
    protected void paintComponent(Graphics g2) {
        g = (Graphics2D)g2;
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        dimFrame = getSize();
        setBackground(Color.WHITE);
    }
    public Dimension getPreferredSize() {
        return new Dimension(700, 500);
    }
    void drawCrosshair(double x, double y) {
        double maxx = dimFrame.getWidth();
        double maxy = dimFrame.getHeight();
        g.setPaint(Color.BLACK);
        g.draw(new Line2D.Double(0, y, maxx, y));
        g.draw(new Line2D.Double(x, 0, x, maxy));
    }
}
public class pra {
    public static void main(String[] args) {
        JFrame jFrame = new JFrame();
        ChartPanel chartPanel = new ChartPanel();
        jFrame.add(chartPanel);
        jFrame.pack();
        jFrame.setVisible(true);
        jFrame.setExtendedState(Frame.MAXIMIZED_BOTH);
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}


它以正确的值进入drawCrosshair()方法。我不知道我在做什么错。

最佳答案

您可以只处理drawCrosshair(),并在paint方法中绘制十字准线,该方法将替换paintComponent方法(实际上,我认为您永远不应覆盖paintComponent):

    Graphics2D g;
    Dimension dimFrame;
    int x, y;
    ChartPanel() {
        addMouseMotionListener(this);
        setPreferredSize(new Dimension(700, 500));
    }

    public void mouseMoved(MouseEvent e) {
        x = e.getX();
        y = e.getY();
        repaint();
    }

    public void mouseDragged(MouseEvent e) {
    }

    public void paint(Graphics g2) {
        super.paint(g2);
        g = (Graphics2D) g2;
        g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        dimFrame = getSize();
        g.clearRect(0, 0, dimFrame.width, dimFrame.height);//clears previous drawings
        g.setColor(Color.BLACK);
        g.drawLine(x - 10, y, x + 10, y);
        g.drawLine(x, y - 10, x, y + 10);
    }


这应该做到(实际上,正如我测试过的那样;))

10-06 09:21