【问题标题】:Unable to draw on the image无法在图像上绘图
【发布时间】:2025-12-24 18:15:06
【问题描述】:

其实我需要做的是... 在图像上绘图(通常尺寸很大)。我需要滚动图像以在其上绘图。 为此,我将图像(JLabel)添加到 Jpanel 中,并将 Jpanel 添加到 JScrollPane 中。 现在我可以滚动图像但无法在其上绘图。有人可以帮我弄清楚吗!这是我的代码...`

    JFrame frame = new JFrame("Title");  
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setPreferredSize(new Dimension(800, 800)); 

    JPanel panel = new JPanel(); 

    panel.add(new JLabel(new ImageIcon(image))); 

    JScrollPane jspane=new JScrollPane(panel);
    jspane.setViewportView(panel);
    jspane.add(this); //where i need to draw according to the mouse click
                      //when i tried frame.add(this); i was able to draw only on some  
                      //portion of the image but not able to scroll it.
    frame.add(jspane, BorderLayout.CENTER);

    frame.pack();  

    frame.setVisible(true);

【问题讨论】:

    标签: java swing jpanel jscrollpane jlabel


    【解决方案1】:

    jspane.add(this);

    不要尝试将组件添加到滚动窗格。组件只能添加到视口中(您在创建 JScrollPane 时就这样做了。

    如果你想在标签上绘图,那么你需要扩展 JLabel 并重写 paintComponent() 方法来在图像上进行自定义绘图。

    请阅读 Custom Painting 上的 Swing 教程中的部分以获取示例。

    【讨论】: