Adding a Custom Image to a GUI based Game - java

I am in the process of programming a game and I would like to change the black background to a custom image. How can this be done?
setBackground(Color.BLACK);
I've tried to add this inside the method:
new ImageIcon("src/image/TheSnakeBody.png")
But it did not work.
Any suggestions?
Here's the code:
private void RunningBoard() {
addKeyListener(new KeysAdapter());
setBackground(Color.BLACK);
setFocusable(true);
setPreferredSize(new Dimension(B_WIDTH, B_HEIGHT));
Icons.IconsUsed();
RunningGame();
}

Well, there's actually no such thing as background in game development.
Games, as being rendered, aren't static/moving images on other image. The whole screen is being rendered many times a second.
So to achieve the "effect" of black background, you need to first draw a black rectangle on your screen, and then your other figutres.
setColor(Color.BLUE);
drawRect(0, 0, 1920, 1080); // or your screen size

Related

Cant draw a shape to a specific panel in a NetBeans GUI

I'm trying to make a simple application to draw shapes to a panel in a jFrame. The GUI is a NetBeans generated jFrame. The application has three panels. the first two hold button groups to select the shape and a color. There's a button to draw the shape to the third panel once the selections are made.
What the GUI looks like
Unfortunately I'm having no love and can't make it work. For now I just want to get the button to draw a shape then I'll add the button functionality. Here's the code I have so far.
private void btnDrawShapeActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
Draw shape = new Draw();
pnlDrawPad.add(shape); //pnlDrawPad is the name of the jPanel
shape.drawing();
}
import javax.swing.*;
import java.awt.*;
public class Draw extends JPanel{
public Draw(){
super();
}
public void drawing(){
repaint();
}
//#Override <-- gives error "method does not override or implement a method from a supertype"
public void paintCompnent(Graphics g){
super.paintComponent(g);
g.setColor(Color.RED);
g.drawString("Hello World!",40,30);
}
}
When I click the "Draw Shape" button nothing happens. I've been searching for a couple days now and am not finding the answer. Actually, its making me more confused as to what to do.
How to deal with this?
Don't keep creating new panels for each shape.
Instead you need a single panel with an ArrayList of objects you want to paint. Then you customize the paintComponent(...) method of the panel to iterate through all the objects in the panel and paint them.
So you button will just add another object to the ArrayList and then invoke repaint() on the panel.
Check out Custom Painting Approaches. The DrawOnComponent example shows how to paint a Rectangle objects from an ArrayList to get you started.
I found that with NetBeans you don't need to Override the paintComponents() method. Since all the GUI stuff is done when you design it, you merely need to add the drawings to the panel or what ever you need to do. I found you that by declaring and instantiating a 2D graphics object then drawing it to the place you want.
private void btnDrawShapeActionPerformed(java.awt.event.ActionEvent evt) {
int centerX;
int centerY;
Graphics2D drawFx = (Graphics2D)pnlDrawPad.getGraphics();
drawFx.setColor(Color.ORANGE);
centerX = (int)(458*Math.random());
centerY = (int)(440*Math.random());
drawFx.fillOval(centerX-50, centerY-50, 100, 100);
drawFx.dispose();
}
Worked like a charm so now every time I push the draw shape button it draws a shape to the panel in a different location every time. I've since put in the radio button functionality to change shape color and fill and added a button to clear the screen.
Not sure if this is the ideal way to do it but for this stupid simple little program it works well enough and I'm done stressing over it.

Paint an image on parent component

I'm developing an application that has to draw a map.
I have a JPanel grid that contains a 2D array of JPanel cells.
I'm using this:
public class myCell extends JPanel {
...
#Override
public void paint(Graphics g){
super.paint(g);
if (imageForeground != null) {
g.drawImage(imageForeground, 0, 0, this);
}
}
#Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(imageBackground, 0, 0, this);
}
}
This draws my background image, and my foreground image on top of it.
I want to draw an image in a cell, that will be displayed on TOP of the OTHER cells, ie, draw an image bigger than the cell, FROM the cell, something like:
#Override
public void paint(Graphics g){
super.paint(g);
super.drawImage(imageForeground, 0, 0, this);
or
g.drawImage(imageForeground, 0, 0, this, overflowFromPanel == true);
}
or if it's possible, tell the image that it CAN be bigger than my Cell.
For more informations:
The background cells are all 1*1 in size. The foreground image must be drawn over ALL the background images it spread over.
For example, if I draw a 3*3 hours at the [1,1] square, it must be over the [1,1], [1,2], [1,3], [2,1], etc...
Custom painting is done by overriding the paintComponent() method, not paint().
I'm developing an application that has to draw a map.
So the background image is the map and covers the entire panel. The house would then be painted on top of the map.
So in the parent component you override paintComponent() and paint the background image
Then in the CellPanel, you override paintComponent() and paint the foreground image. Although, why don't you just use a JLabel with an ImageIcon so you don't need to do custom painting?
if I draw a 3*3 hours at the [1,1] square,
Then you need to add your house image to 9 cells .
The other option is to forget about defining your map into cells. Instead you create a custom object with two properties:
Point - a point on the background map
Image - the image to paint at that point.
Then you add this custom Object to an ArrayList. Then in the paintCompont() method of the main panel you iterate through this ArrayList and paint each image at its specified location.
#Overide
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(...); // paint the background
for (each item in the ArrayList)
{
Point p = item.getPoint();
Image image = item.getImage();
g.drawImage(...);
}
}
Edit:
On a side note: the background is a different image for every cell.
Why are you using cells? It sounds like you have a fixed size grid. So you can just paint the individual cell images to a larger BufferedImage that makes a single background image for all the cells. Then you can just paint houses over top of the background.
Another option is to use the OverlayLayout. It allows you to stack two panels on top of one another.
So the logic would be something like:
JPanel panel = new JPanel();
panel.setLayout( new OverlayLayout(panel) );
panel.add( foregroundPanel );
panel.add( backgroundPanel );
You would need to:
Set the "foregroundPanel" transparent.
Both panels would override the paintComponent(...) method to do the custom painting.
Set the size of both panels to be the same.
Or you could use a JLayeredPane.

Rendering a 2d image in java

I am fairly new to java programming and I am trying to make a simple game however, I need to render my image I have made here is the code I put in eclipse:
public class MainMenu extends JFrame{
public static void main(String[] args){
new MainMenu();
}
public MainMenu(){
this.setSize(300, 450);
this.setLocationRelativeTo(null);
this.setResizable(true);
Toolkit tk = Toolkit.getDefaultToolkit();
Dimension dim = tk.getScreenSize();
int xPos = (dim.width / 2) - (this.getWidth() / 2);
int yPos = (dim.height / 2) - (this.getHeight() / 2);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setLocation(xPos, yPos);
this.setTitle("Frame For Flamedash Testing");
this.setVisible(true);
}
public void paint(Graphics g){
Image img1 = Toolkit.getDefaultToolkit().getImage("mainmenuscreen.png");
g.drawImage(img1, 20, 20, null);
} // public void paint(Graphics g)
public void putit() {
boolean MainMenu = true;
while (MainMenu == true){
repaint();
}
}
}
When I put that it is all fine and it does not give me any errors what so ever then I run it and it shows the frame but shows no picture than I full screen it because I set re-sizable true and it shows the default color in one spot with the size I set the frame too and another one identical but on the corner and black everywhere else. Any help to rendering this .png image will help, thank you in advance.
Don't override paint() in a JFrame.
The easiest way to display an image is to use a JLabel with an Icon.
Read the section from the Swing tutorial on How to Use Icons for more information and examples. The tutorial will show you how to better structure your code.
The tutorial also has a section on Custom Painting, if you really want to paint the image yourself. Custom painting is done by overriding the paintComponent() of a JPanel and then you add the panel to the frame.
First of all, in your paint method you should always call super.paint, else you break the paint chaining.
As for your issue,
You can call the repaint to force the painting. Keep a variable to hold the instance in your main and call repaint :
public MainMenu() {
...
repaint();
}
Note that loading an image from the paint method is a really bad idea as it will be loaded each time the frame is painted.
You've got several problems in that code including:
Drawing directly within the JFrame, something that can have unpleasant side effects
Trying to read in an image from within a painting method.
Your actual problem is often due to specifying the wrong path to the image, and to solve this you need to identify the actual user's directory that Java is looking at as the base of the path. This can be found by calling
System.out.println(System.getProperty("user.dir"));

How to put or draw stable image background in java

I'm having problems with putting a stable image background.
I successfully create/draw an image background but when I consecutively run it many times, the image is not showing. The background image seems to be not stable. When I drag the frame to a side of my laptop screen, the image is being erased. How do I create/draw a stable background image that doesn't flicker or erased when dragged?
This code below is what I used for my background image:
public void paint( Graphics g ) {
super.paint(g);
g.drawImage(img, -30, 0, null); //draw image to background
}
Use the JLabel.setIcon(Icon icon) method.
The benefit of this is you don't need to overwrite any method to put a background.
Indeed you can also use JLabel in alternative to JPanel, if you want a container that has an image background. Below can explain this trick in code:
public class JPanelWithBackground extends JLabel {
public JPanelWithBackground() {
add(new JButton("I can attached to JLabel? Isn't cool? "));
setBackgroundImage("path_to_image.png");
}
public void setBackgroundImage(String imagePath) {
setIcon(new ImageIcon(imagePath));
}
}

Painting new panel on top of another one

I have a program where the base panel is just drawing the background (trees, water, etc), and i have a player and other objects moving around the screen. I don't want to call repaint() on the whole thing because it slows me down because it repaints the whole thing. When I try to add a new panel on top that will be repainted a lot and handle moving objects, nothing happens in my code. This is what I have in the constructor for the first
public GamePanel()
{ //some code
top = TopPanel();
top.setSize(this.getSize());
add(top);
//some more code
}
and then in the class for the toppanel
public TopPanel()
{
}
public void paintComponent(Graphics g)
{
i.drawItem(//);
player.draw(//fields);
}
And no matter what I do, I can't get anything to show up on the panel when i run it.
My general approach when rendering a complex but static 'background' with other things painted on top is to draw the background to a BufferedImage and simply redraw the image before painting the dynamic parts.

Categories