【发布时间】: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。