java - 当我滚动放置的图像时,自行创建的图形消失

标签 java swing

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

但是,我仍然找不到代码中的错误。我觉得我已经按照那里的答案建议做了。

我想要实现的目标很简单;我想从 JFileCoser 选择一个文件(png 图像),然后当我单击 map 时能够将位置添加到该 map 。该位置应该用三角形指出。该图像比它所在的边框大,因此它应该是可滚动的。

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

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

最佳答案

then be able to add locations to that map when I click on the map.

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

您只能绘制一个标记。 PaintComponent() 删除之前的标记。

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

查看 Custom Painting Approaches 中的 DrawOnComponent 示例有关此方法的工作示例。

关于java - 当我滚动放置的图像时,自行创建的图形消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43871770/

相关文章:

java - 有没有办法一次性加载 Spring Boot 应用程序中的配置?

java - 获取两个文本的相似度百分比

Java,Swing - 无法在 JFrame 上画线

java - 如何以绝对定位将组件添加到 JComponent 中?

java - 将 JComboBox 设置为表列不起作用

java - 实例与对象 : The unclear debate

Java 异常没有从 db2 控制台返回相同的异常消息?

java - 如果实体的祖先不存在,是否会创建它(Java API)?

java - 我无法在 JPanel 上查看 BufferedImage 图像

Java Mail API 密码验证