I’m attempting to create a simple point-n-click adventure game in Java. I’m currently trying to get the fundamental aspect of it down that is drawing images on the screen. The scenario is going to be the same almost all the time whereby I will need to draw a background image and then several other images (characters etc) over the top of the background. Later on I will need to move character images, I imagine this will involve needing to draw the background again followed by the same character images but moved slightly.
I was recently working under the idea of using ‘Graphic2D’ and that’s why you will see it popup in the code below. My original idea was to load an image and add it to a jlabel. Then use setLocation() to position the image in the frame.
Code:
public static Graphics2D Graphic = LoadImg("Images/Backdrops/Outside1.png").createGraphics();
//Graphic.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
//Create graphic that will hopefully hold all images displayed on the JFrame.
public static void main(String[] args)
{
JFrame Window = new JFrame();
Window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Window.setSize(1000, 625);
Window.setVisible(true);
//Setup window using swing
Window.getContentPane().add(DrawImg("Images/Backdrops/Outside1.png",500,0));
//Window.getContentPane().add(DrawImg("Images/Characters/Test.png",500,0));
}
public static JLabel DrawImg(String ImageLoc, int x, int y)
{
BufferedImage Image = LoadImg(ImageLoc);
//Graphic.drawImage(Image, x, y, null);
//Graphic.dispose(); //!
JLabel ReadyLabel = new JLabel(new ImageIcon(Image));
ReadyLabel.setLocation(x,y); //Doesn't seem to maneuver the image?
return ReadyLabel;
}
public static BufferedImage LoadImg(String ImgPath)
{
BufferedImage buffer = null;
try
{
buffer = ImageIO.read(new File(ImgPath));
}
catch (Exception e){}
return buffer;
}
setLocation() however does not place the image where specified. There is also the problem of only displaying one image at a time. How can I accomplish these two things? Do I need to use either Graphic2D or Canvas?
Bookmarks