2016-07-02 112 views
0

我有兩個擴展JPanel的類:MapPanel和CityPanel。我試圖將一個CityPanel繪製到MapPanel中,但沒有出現。我不明白爲什麼如果我以相同的方式添加一個JButton它將被完美顯示。 下面的代碼:將JPanel繪製到JPanel中

public class PanelMap extends JPanel { 

    public PanelMap() { 
     CityPanel city = new CityPanel(); 
     city.setVisible(true); 
     this.add(city); 
    } 

    @Override 
    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 
    } 

} 



public class CityPanel extends JPanel { 

    private BufferedImage image; 

    public CityPanel() { 
    } 

    @Override 
    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     g.drawString("Test", 0, 0);  } 

} 

編輯:

我--cityMap中的代碼。它顯示字符串,但沒有圖像。

public CityPanel(String filePath, int red, int green, int blue) { 
     this.image = colorImage(filePath, red, green, blue); 
     this.setSize(100, 100); 
    } 

    @Override 
    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     g.drawImage(image, 50, 50, null); 
     g.drawString("sdjkfpod", 50, 50); 
    } 
+1

'@Override protected void paintComponent(Graphics g){ super.paintComponent(g); '這個代碼完全沒有意義。它所實現的一切就是確保該方法完全執行如果重寫的方法丟失的情況。 –

+1

由於'CityPanel'不提示大小,'PanelMap'具有默認的'FlowLayout',因此城市面板將爲0x0像素,並且不會顯示。添加一個紅色的'LineBorder',以證明它自己更普遍:爲了更好的幫助更快,發佈一個[MCVE]或[簡短,獨立,正確的例子](http://www.sscce.org/)。 –

+0

給你的內部面板的大小... –

回答

1

能否請您更換您的以下PanelMap.java構造:

public PanelMap() { 
    CityPanel city = new CityPanel(); 
    city.setVisible(true); 
    this.add(city); 
} 

通過下面的構造:

public PanelMap() { 
    String filePath = "C:\\...\\city2.png"; 
    CityPanel city = new CityPanel(filePath, 0, 255, 255);  
    this.setLayout(new BorderLayout()); 
    this.add(city, BorderLayout.CENTER);   
} 

和看到的結果?

繼已經作了修改你的代碼:

  • 聲明city.setVisible(true);被刪除,因爲它根本不需要 。
  • 聲明this.add(city);確實被加入到CityPanel PanelMapCityPanel拿起非常小的空間,並期待爲 非常小的矩形。這就是使用BorderLayout的原因 。

PanelMapDemo.java增加PanelMapJFrame,並創建一個可執行的例子。

public class PanelMapDemo extends javax.swing.JFrame { 
private static final long serialVersionUID = 1L; 

public static void main(String[] args) { 
    javax.swing.SwingUtilities.invokeLater(new Runnable() { 
     public void run() { 
      PanelMapDemo demoFrame = new PanelMapDemo("PanelMapDemo"); 
      demoFrame.setVisible(true); 
     } 
    }); 
} 

public PanelMapDemo(String title) { 
    super(title); 
    setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE); 
    add(new PanelMap()); 
    setSize(new java.awt.Dimension(400, 200)); 
    setLocationRelativeTo(null); 
} 
} 

在我的系統當原始圖象是:

enter image description here

MapPanel圖像改爲:

enter image description here

希望,這會有所幫助。

+0

Hi @ user1315621你看過我的回答嗎? –

+0

不要忽視'包裝()'封閉的框架。 – trashgod