2017-05-09 56 views
1

我知道,以前曾詢問過非常類似的問題。例如: 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 
+2

這將簡化一些東西,如果不是試圖有'PlaceMarker'延長'JComponent',你做它只是協調邏輯類,然後直接在'paintComponent'它畫在你的面板('ImageContainer'?) 。不利的一面是,它會讓一些東西像工具提示變得更復雜一些。更重要的是,你應該嘗試用一個[最小的,完整的例子](http://stackoverflow.com/help/mcve)來更新你的問題,它會重現這個問題。此外,您需要刪除對'PlaceMarker.paintComponent'內的'repaint()'的調用。 – Radiodef

回答

2

然後就可以當我點擊地圖時向該地圖添加地點。

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

你永遠只畫一個標記。 paintComponent()刪除以前的標記。

所以,你需要保持你要畫,然後遍歷列表繪製的所有標記,這些自定義標記的名單。

查覈在Custom Painting Approaches發現這種方法的工作示例DrawOnComponent例子。

相關問題