2016-07-02 113 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