Jump to content
  • Advertisement
Sign in to follow this  
  • entries
    5
  • comments
    0
  • views
    371

AWT GUI Facade (3): Display an image

Sign in to follow this  
phylyp

1040 views

The facade seen in the previous article has only an interface with its methods. It is also possible to enrich a facade with additional interfaces, connected to each other by various means. To illustrate it, I propose to add image management. This addition also makes it possible to present another design pattern: the Factory Method Pattern.

This post is part of the AWT GUI Facade series.

In graphic libraries, it is generally not possible to directly access the raw data of an image, it is always necessary to go through an identifier or a class to apply some processing. Knowing this, a relevant approach is to encapsulate what makes it possible to process the image in a dedicated class, for example:

awtfacade03a-1024x338.png

Compared to the previous article, the following methods have been added to the GUIFacade interface:

  • The createImage() method creates an Image from the name of a file. In doing so, we are using the Factory Method pattern, which allows us to abstract the creation of objects, and whose creation process depends on inheritance. In this case, the user of the createImage() method does not know which implementation of the Image interface will be used. This choice depends on the class that implements GUIFacade interface, whose details are not necessarily known to the user, since it is a facade.
    Once again, the idea is to free the user of specific features, and let him focus on the problem he has to deal with, in our case the rendering of a 2D tile game.
  • The drawImage() method is used to draw an image at (x, y) coordinates.

Other methods dedicated to the creation and processing of images can be imagined, these are only examples among others.

The Image interface is used to represent access to an image managed by the graphics library. Methods can be proposed to work with an image. In our example, the getWidth() and getHeight() methods return the width and height of the image. Other methods can be imagined, such as a draw() method that would draw the image, instead of the one within the GUIFacade interface.

For the implementation of the facade, we still use the AWT library. For the Image interface implementation, an AWTImage class is proposed:

public class AWTImage implements Image {

    private BufferedImage image;

    @Override
    public int getWidth() {
        if (image == null) {
            throw new RuntimeException("The image was not loaded");
        }
        return image.getWidth();
    }

    @Override
    public int getHeight() {
        if (image == null) {
            throw new RuntimeException("The image was not loaded");
        }
        return image.getHeight();
    }
    
    void loadImage(String fileName) {
        try {
            image = ImageIO.read(this.getClass().getClassLoader().getResource(fileName));
        } catch (IOException ex) {
            throw new RuntimeException("Error when reading "+fileName);
        }
    }
    
    void draw(Graphics graphics,int x,int y) {
        graphics.drawImage(image, x, y, null);
    }
}

The AWTImage class holds an image reference to a java.awt.image.BufferedImage. getWidth() and getHeight() methods return the width and height of the image. The other two methods are not part of the facade, and are invisible to its users. They are used by the AWTGUIFacade class to load the image (loadImage() method) and display it in a java.awt.Graphics (draw() method):

public class AWTGUIFacade implements GUIFacade {

    ...

    @Override
    public Image createImage(String fileName) {
        AWTImage image = new AWTImage();
        image.loadImage(fileName);
        return image;
    }   
 
    @Override
    public void drawImage(Image image, int x, int y) {
        if (!(image instanceof AWTImage))
            throw new IllegalArgumentException("Invalid image type");
        AWTImage awtImage = (AWTImage) image;
        awtImage.draw(graphics,x,y);
    }   

}

This new version of the facade can be used in the following way to display a window with an image:

public static void run(GUIFacade gui) {
    Image titleImage = gui.createImage("title.png");
    gui.createWindow("AWT Graphic User Interface Facade",
        titleImage.getWidth(),titleImage.getHeight());
    while(!gui.isClosingRequested()) {
        if (gui.beginPaint()) {
            gui.drawImage(titleImage,0,0);
            gui.endPaint();
        }
    }      
    gui.dispose();
}

The image is created from the file “title.png” (1. 2), a window of the size of the image is also created (l.3), and as long as the game is not finished (l. 5), the drawing is started (1. 6), the picture is displayed (1. 7) and the drawing is ended (1. 8).

The code of this post can be downloaded here:

To compile: javac com/learngameprog/awtfacade03/Main.java
To run: java com.learngameprog.awtfacade03.Main

Next post in this series

View the full article

 

Sign in to follow this  


0 Comments


Recommended Comments

There are no comments to display.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Advertisement
  • Advertisement
  • Blog Entries

  • Similar Content

    • By Blink4Blink
      I'm working on my first Android game and I have a few questions.
      I need to scale the graphics for different screen sizes/resolutions. I'm working in 16:9 and plan to use letter boxing to maintain this aspect ratio.
      Everything is fine for standard screen resolutions. Going from 320:180 to 640:360, one pixel just becomes four. I'm a little confused though as to what happens when you letterbox on a screen with a unusual resolution.
      Say, just for exsample, my original graphics are 160:90. Then to fit the devise I stretch everything by 1.1 and end up with a final resolution of 176:99. Its still 16:9 but now everything is a mess.
      If I had a sprite that used to be at x-33 y-33 it's new location would now be at x-36.3 y-36.3. Would I just drop the 0.3 of a pixel, round down and accept that it's no longer in its exact position? 
      Secondly what exactly happens when you stretch images by an amount like 1.1? How dose it decide what pixels to add to the image to make it bigger? 
    • By Aymen.Khelifi
      I have been fascinated by programming before 8 years from now. The journey took me from someone who loves to be software engineer to be a networks engineer. I work as full time IP networks engineer.
      Well,  I am a great fun of indie games developers. I have been following Dev-Logs for several indie game developers for a while. In the previous years many ideas of games have been floating in my mind and finally I took the decision to start my own small game project.
      I have been planning for the last 2 weeks for my game. I have decided to write the whole game and engine myself. My estimations are : 
      Because I am doing this as side project the whole idea ( a 2D platformer ) will take me between 6 months to 1 year. The Game Engine will be developed in parallel with the game I am probably going to Use Java LWJGL or any other OpenGl library  I should find a way to target my audience ( probably Youtube channel and dev-logs)  Perfectioning the game might have a longer duration than the development of it. I will publish it when it meets the 95% of my expectations If There is any piece of advice of how to start the journey, It will be very helpful. If you have any thoughts about my plan please share it with me. If you have any guidance about how to use this platform I would be more than happy to hear from you.
      I am just a man who lost his way when making his career related decisions and he is doing a lot of things for fun. 
      Thank you.
    • By MasqCrew
      Hey guys,
      I'm putting together a little thing in Python, a city builder of sorts. Nothing fancy, to be sure. The user will click on buttons to purchase items. In-game currency will be collected via taxes. I'd like to include population growth and pretty much anything that the big city builders keep track of. 
      One of the things I'm not sure how to do is simulate population growth. Each house will have a capacity, so it would be easy to say that a population couldn't grow beyond a certain point (to keep things simple), or if the population grew beyond residential capacity, there would be a homeless population to keep track of (maybe later). What factors would affect population? I'm thinking several things but not sure how to include them in formulas. Building a school could encourage more people to move in. Building other service buildings would help as well. This may not be a game design question (rather something for another forum), but how would you factor in multiple things to raise or lower the chances the population grows?
      And money won't be the only metric. Farms will produce food, which might be needed in order to build restaurants. 
      The pic I've attached shows the very basic and early GUI I'm playing with. Since there won't be any other graphics beyond the buttons (and maybe graphs later), there will be lots of buttons and pages to produce a lot of interactions and gameplay methods.
      I'd love any ideas you have to offer.

    • By Tony Vilgotsky
      Hello, dear colleagues!
      Recently I had a long evening of reflections on the topic, what makes a video game an indie game? Of course, indie projects are the whole niche in this days, but it seems sometimes that when some people are talking about “indie games”, they just don’t know what they are talking about. For some reason many people think that being indie means to be a low-qualified person who is obligated to produce tons of clones of classic games which were hits decades ago. And when they come to game making, they even don’t consider an opportunity to create something more original and interesting. They deliberately produce all these clones. Moreover, with deliberately downgraded graphics, sound and mechanics, which makes sense when it comes to retro scene, but… retro scene is a separate scene and all the indie games don’t have to fit its standards. And then they complain: why nobody is buying this? I think that the answer is obvious: modern gamers prefer modern graphics. So why shoot your own leg, filling your game with pixels, which aren’t even “an art”?
      I’m even silent about the gameplay clones. I think that there should be fewer of them, because indie development is just that thing that gives you freedom to be more original and implement bolder decisions. The world is playing Tetris for 200 years already (correct me if I’m wrong) - and nobody wants to play Tetris with crocodiles instead of bricks.
      It’s sometimes even getting funny: recently I’ve joined a new team (as a junior writer), making a 3D action/adventure game Between Realms with Unreal engine. This is an indie team and indie game, but the goal is to produce a major hit. The game incorporates modern 3D graphics, cutscenes and professional voice overs. And when we posted some stuff from it on the Internet, some people just didn’t believe that we are actually an indie team! I think it’s because modern indie projects almost always belong to the pixel scene or notably simplified from the visual side. So, when we show our materials, some people don’t believe that we belong to indie niche.
      Does it mean that one has to produce simple games with poor 2D pixel graphics to be considered an indie developer?
      From my (and my colleagues’) point of view, indie development must be not a compromise between production speed, expense and quality, but a freedom to create a conceptual product which is not limited by obligatory to sell millions of copies. Those who are tied by this obligatory, are forced to produce standardized, so to say, “tentpole” projects. But with modern technologies the developer is able to create nice, commercially promising, but still an independent project. As developers, we want to raise the bar of indie standard and wish all the rest to reach the same with the games which would be not only original in terms of gameplay but also attractive visually.
      What are you thoughts on this matter? Can a project with budget over $100 be called an indie project? What are the main features of typical indie game? What really makes a game an “indie” game?
    • By vvoodenboy
      Hi!
      My name is... nobodycaresbecauseitsnotimportant.
      I'm working on my own card game. I'm just in a stage of connecting some 'dots' of game's mechanics.
      I'm looking for a concept / 2D artist - because its time to give it some shape - I've a concept of a dark fantasy world where I want to place the plot but there is a lot of space for creativity.
      If you are interested please shout here or on discord (vvoodenboy#3207) or vvoodenboy@gmail.com.
      Have a nice day!
      V
  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!