我知道以前曾经问过类似的问题。例如这里: 1- Disappearing components in JScrollPane 和2- Drawing in JPanel disappears when scrolling or ressizing the frame。
但是,我仍然无法在代码中找到错误。我觉得我已经完成了那里的答案。
我想要实现的是简短的;我想从JFileChoser中选择一个文件(一个png图像),然后当我点击地图时能够向该地图添加位置。应该用三角形指出位置。图像比放置的边框大,所以它应该是可滚动的。
我已经成功完成了所有这些,但问题与上述两个问题相同 - 当我滚动图像时,我放在图像上的三角形消失了。从我的代码中取出一些:
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
答案 0 :(得分:2)
然后,当我点击地图时,能够向该地图添加位置。
super.paintComponent(g);
g.fillPolygon(xValuesArray, yValuesArray, 3);
你只画一个标记。 paintComponent()删除以前的标记。
因此,您需要保留要绘制的这些自定义标记的列表,然后遍历List以绘制所有标记。
查看Custom Painting Approaches中找到的DrawOnComponent
示例,了解此方法的工作示例。