-1

实际上我需要做的是......在图像上绘制(通常尺寸很大)。我需要滚动图像以在其上绘图。为此,我将图像(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);
4

1 回答 1

1

jspane.add(this);

Don't try adding components to a scrollpane. Components can only be added to the viewport (and you did that when you created the JScrollPane.

If you want to draw on the label, then you need to extend JLabel and override the paintComponent() method to do your custom painting on top of the image.

Read the section from the Swing tutorial on Custom Painting for an example.

于 2013-11-11T16:31:31.200 回答