I am new to swing and I have been following the tutorials at the Oracle website. So I have an imagePanel class using which, I paint an image onto a JPanel
. Next, I need to draw shapes over this image. So I call the drawShapes
function in the paintComponent
method of the imagePanel class. The issue that I am facing is, whenever I draw any shape say rect
or oval
it doesnt not draw the shape according to the position I specify for the y-axis. It only takes the x-axis into account. So ideally,
fillOval(30,70,10,10)
is tantamount to fillOval(30,30,10,10)
Am i doing something wrong or is there some way to overcome this?
public class ImagePanel extends JPanel {
private Image img;
public ImagePanel(String loc)
{
this(new ImageIcon(loc).getImage());
}
public ImagePanel(Image img) {
this.img = img;
Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
setPreferredSize(size);
setMinimumSize(size);
setMaximumSize(size);
setSize(size);
setLayout(null);
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(img, 0, 0, null);
renderShapes(g);
}
private void renderShapes(g){
Graphics2D g2d = (Graphics2D)g;
g2d.fillOval(20,70,10,10);
g2d.fillRect(120,40,10,10);
}
}
EDIT The renderShapes
method for the screenshot provided is posted below.
private void renderShapes(g){
Graphics2D g2d = (Graphics2D)g;
g2d.fillRect(220,50,10,10);
g2d.fillRect(20,140,10,10);
}