Reputation: 3372
I have two classes that extend JPanel: MapPanel and CityPanel. I am trying to draw a CityPanel into a MapPanel but nothing appears. I do not understand why if I add a JButton in the same way it will be displayed perfectly. Here's the code:
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); }
}
EDIT:
I have this code in CityMap. It display the string but no the image.
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);
}
Upvotes: 0
Views: 117
Reputation: 2652
Could you please replace your following constructor of PanelMap.java
:
public PanelMap() {
CityPanel city = new CityPanel();
city.setVisible(true);
this.add(city);
}
By following constructor:
public PanelMap() {
String filePath = "C:\\...\\city2.png";
CityPanel city = new CityPanel(filePath, 0, 255, 255);
this.setLayout(new BorderLayout());
this.add(city, BorderLayout.CENTER);
}
and see the result?
Following changes have been made to your code:
city.setVisible(true);
is removed since it is not
required at all.this.add(city);
was indeed adding CityPanel
to
PanelMap
but CityPanel
took up very small space and looked as a
very small rectangle. This is the reason the BorderLayout
has been
used.Following PanelMapDemo.java
adds PanelMap
to a JFrame
and creates an executable example.
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);
}
}
On my system when the original picture was:
Your MapPanel
changes the picture to:
Hope, this helps.
Upvotes: 1