Reputation: 47
I have around 10 sets of coordinates for 10 polygons that I need to draw on an image Label. This is what I have coded so far:
But since I cannot call paintComponent separately , I am calling it while instantiating the JLabel and that leads to the problem. At the end , I am just getting the last Polygon drawn on the image because everytime the new jLabel is created. Can someone point out how can this be improved so that I could draw multiple polygons on the same JLabel.
private void setMapImage()
{
Queries queries = new Queries(dbConnection, connection);
List<ArrayList<Integer>> allGeo = queries.getBuilding();
for(int i = 0; i < allGeo.size(); i++)
{
int[] xPoly = queries.separateCoordinates(allGeo.get(i),0);
int[] yPoly = queries.separateCoordinates(allGeo.get(i),1);
poly = new Polygon(xPoly, yPoly, xPoly.length);
poly = new Polygon(xPoly, yPoly, xPoly.length);
background=new JLabel(new ImageIcon("image.JPG"),SwingConstants.LEFT)
{
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.YELLOW);
g.drawPolygon(poly);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(820, 580);
}
};
}
background.setVerticalAlignment(SwingConstants.TOP);
frame.add(background);
background.setLayout(new FlowLayout());
frame.setVisible(true);
}
Upvotes: 0
Views: 599
Reputation: 2076
I think you have to iterate through the polygons you have in the paintComponent method of the JLabel. Before that you have to add all the poligons to a list.
For instance:
private void setMapImage()
{
Queries queries = new Queries(dbConnection, connection);
List<ArrayList<Integer>> allGeo = queries.getBuilding();
List<Polygon> polyList = new ArrayList<Polygon>();
for(int i = 0; i < allGeo.size(); i++)
{
int[] xPoly = queries.separateCoordinates(allGeo.get(i),0);
int[] yPoly = queries.separateCoordinates(allGeo.get(i),1);
poly = new Polygon(xPoly, yPoly, xPoly.length);
polyList.add(poly);
}
background=new JLabel(new ImageIcon("image.JPG"),SwingConstants.LEFT)
{
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.YELLOW);
for(final Polygon poly : polyList){
g.drawPolygon(poly);
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(820, 580);
}
};
background.setVerticalAlignment(SwingConstants.TOP);
frame.add(background);
background.setLayout(new FlowLayout());
frame.setVisible(true);
}
Upvotes: 0