【问题标题】:Self created graphics disappear when I scroll the image they've been placed on当我滚动放置它们的图像时,自行创建的图形消失了
【发布时间】:2017-05-09 23:11:08
【问题描述】:

我知道以前有人问过非常相似的问题。例如这里: 1-Disappearing components in JScrollPane 和 2-Drawing in JPanel disappears when scrolling or ressizing the frame

但是,我仍然无法在我的代码中找到错误。我觉得我已经完成了那里的答案。

我想要达到的目的很简单;我想从 JFileChoser 中选择一个文件(一个 png 图像),然后当我单击地图时能够将位置添加到该地图。位置应该用一个三角形来指出。图片比它所在的 Border 大,所以它应该是可滚动的。

我已经做到了所有这些,但问题与上述两个问题相同 - 当我在图像上滚动时,我放置在图像上的三角形消失了。我的代码中的一些内容:

public PlaceMarker(int xCoordinate, int yCoordinate){
    setBounds(xCoordinate, yCoordinate, 50, 50);
} //This class extends JComponent

@Override
protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.fillPolygon(xValuesArray, yValuesArray, 3);

    repaint();
}

我添加图片的按钮:

JMenuItem newImage = new JMenuItem("New Image");
    newMap.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            String directory = System.getProperty("user.dir");
            fileChooser = new JFileChooser(directory);
            int answer = fileChooser.showOpenDialog(MainFrame.this);
            if(answer != JFileChooser.APPROVE_OPTION)
                return;
            File file = fileChooser.getSelectedFile();
            String filePath = file.getAbsolutePath();
            if(image != null)
                remove(scrollPane);
            image = new ImageContainer(filePath);
            scrollPane = new JScrollPane(image);
            scrollPane.setMaximumSize(image.getPreferredSize());

            add(scrollPane, BorderLayout.CENTER);
            pack();
            validate();
            repaint();
        }
    });

我的 ImageClass 中也有这个方法:

@Override
protected void paintComponent(Graphics g){
    super.paintComponent(g);
    g.drawImage(image.getImage(), 0, 0, this);
} //This class extends JPanel

【问题讨论】:

  • 如果不是尝试让 PlaceMarker 扩展 JComponent ,而是将其设为仅具有坐标的逻辑类,然后将其直接绘制在面板的 paintComponent 中( ImageContainer?)。这样做的缺点是它会使工具提示等一些事情变得更加复杂。更重要的是,您应该尝试使用重现问题的minimal, complete example 更新您的问题。此外,您需要删除对 repaint() 内部的调用 PlaceMarker.paintComponent

标签: java swing


【解决方案1】:

然后,当我单击地图时,就可以将位置添加到该地图。

super.paintComponent(g);
g.fillPolygon(xValuesArray, yValuesArray, 3);

你只能画一个标记。 paintComponent() 会移除之前的标记。

因此,您需要保留要绘制的这些自定义标记的列表,然后遍历列表以绘制所有标记。

查看Custom Painting Approaches 中的DrawOnComponent 示例,了解此方法的工作示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-22
    • 2019-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多