简体   繁体   中英

Java How can I put an image on a rectangle

This is the code

 player = createEntity(400, 600, 40, 60, Color.BLUE);

private Node createEntity(int x, int y, int w, int h, Color color) {
    Rectangle entity = new Rectangle(w, h);
    entity.setTranslateX(x);
    entity.setTranslateY(y);
    entity.setFill(color);

    gameRoot.getChildren().add(entity);
    return entity;

}

I'm not sure how to put an image to my player, any thoughts?

Java How can I put an image on a rectangle

My suggestion (if this is Swing) is not to use a Rectangle, or else use Rectangle but as part of a larger solution.

Instead I'd create a logical class, perhaps called Entity, that has a position, an image, and a draw method that accepts a Graphics parameter draws its image at whatever position needed, and then create Entity objects. Then within my JPanel's paintComponent method, I'd iterate through all the Entities created, calling their draw method.

First of all, you'll want to use active rendering . This'll prevent you from having all sorts of problems related to refreshing the display, and Java's BufferStrategy automatically handles multi-buffering for you, assuming you request more than one buffer.


Now that you're sure the screen gets updated, when rendering, you can draw a rectangle with a java.awt.Graphics object using the drawRect method. If you would like to fill this rectangle, use fillRect . The Graphics object draws everything in a pre-defined colour. If you would like to change colour, you can call setColor . This method requires a java.awt.Color object as an argument, which allows you to define all possible 64-bit transparent colours using one of the constructors. It also has a few predefined colours, like Color.RED , which is 0xFF0000 .

I recommend you explore all the methods Graphics has to offer, and maybe even look into Graphics2D , which supports a few extra things. Note that most Graphics objects can be cast to Graphics2D , but if you're not sure, you might either want to look into Java's source code (there is an src.zip inside the JDK installation) or use an instanceof check. As a matter of fact, Graphics2D supports drawing shapes like your Rectangle using the drawShape or fillShape method.


For those of you who are curious, 0xFF0000 is a way of formatting colours. It is RGB encoded into hexadecimal ( 0xRRGGBB ). It's also commonly represented #FF0000 in other languages, like CSS (Cascading Style Sheet, used for easily formatting HTML documents)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM