Java - JPanel can't draw background image - java

I am learning how to work with Gui's in java. Currently I'm trying to make a simple program that opens a Gui and draws an image to the background. The problem is that the background is completely white instead of the image.
Code:
Main.java:
package com.flaghacker.buckygame;
public class Main
{
public static void main(String[] args)
{
GuiFrame guiFrame = new GuiFrame();
}
}
GuiFrame.java:
package com.flaghacker.buckygame;
import javax.swing.JFrame;
public class GuiFrame extends JFrame
{
private GuiPanel guiPanel;
public GuiFrame()
{
//General
super("Title");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Size
this.setSize(1100, 650);
this.setResizable(true);
//Components
guiPanel = new GuiPanel();
this.add(guiPanel);
//Final
this.setVisible(true);
}
}
GuiPane.java:
package com.flaghacker.buckygame;
import javax.swing.ImageIcon;
import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.Image;
public class GuiPanel extends JPanel
{
private Image backGround;
public GuiPanel()
{
backGround = new ImageIcon("D:\\Install\\Java Projects\\Testing\\Bucky\\Back.jpg").getImage();
}
#Override
public void paint(Graphics g)
{
super.paint(g);
g.drawImage(backGround, 0, 0, null);
}
}

I test your code and it works ... the possible problem are two
first) your image isn't in
"D:\\Install\\Java Projects\\Testing\\Bucky\\Back.jpg"
i suggested you to use
"D:/Install/Java Projects/Testing/Bucky/Back.jpg"
and verify
Case insensitive.
second) the image Back.jpg have width and height more high of 1100 650 so you display only a top left angle of image

Related

Why is g.drawImage() not drawing to the window?

Trying to draw an image to a JFrame, but only the oval is drawn. Any idea as to why this might be? Images are in the correct folder, and no errors show up in the console.
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.*;
public class DisplayImages extends JFrame
{
private Image background;
private Image pic;
public static void main(String[] args)
{
DisplayImages sf = new DisplayImages();
sf.go();
}
public void go()
{
background = new ImageIcon("images/background.jpg").getImage();
pic = new ImageIcon("images/translucent.png").getImage();
setSize(800,600);
setVisible(true);
}
public void paint(Graphics g)
{
g.drawImage(background,0,0,null);
g.drawImage(pic,20,20,null);
g.drawImage(pic,120,120,null);
g.drawOval(20,100,30,40);
}
}
Result

Java BufferedImage is not draw correctly

I have been wanting to program a 2D game from scratch in Java for a while. The pixel aesthetic is one of my favorites, so I am aiming for a pixel 2D game. However, whenever I try to use BufferedImage to draw my tiles, the tiles become extremely distorted.
The tile drawn is actually bigger than the real tile and it seems like it has been stretched. Basically, say I have a 16x16 tile and I draw it. I can visually tell it is distorted when I run the program, and when I take a screenshot, I can measure the pixels and it has somehow become a 20x20.
I have also noticed that when I set a JFrame or a JPanel in the JFrame to a certain size, it is not the actual size that is produced. In my program I create a 320x320 JPanel and put it in a JFrame, but when I take a screenshot and measure the window, it comes up to about 399x399.
Can someone please tell me how to fix this. I stop every game project because the graphics keep looking like rubbish.
This is the Main class:
package main;
import javax.swing.SwingUtilities;
public class Main {
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
Engine e = new Engine();
e.start();
}
});
}
}
This is the Engine class:
package main;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class Engine {
public JFrame f;
public void initFrame() {
f = new JFrame();
f.setTitle("Something");
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setLocationRelativeTo(null);
}
public void start() {
initFrame();
BufferedImage tree;
try {
tree = ImageIO.read(new File("res/boy_down_1.png"));
Panel p = new Panel(tree);
f.add(p);
f.pack();
} catch (IOException e) {
e.printStackTrace();
}
f.setVisible(true);
}
}
This is the Panel class:
package main;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
public class Panel extends JPanel {
BufferedImage i;
public Panel(BufferedImage image) {
i = image;
this.setDoubleBuffered(true);
this.setPreferredSize(new Dimension(320, 320));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(i, 20, 20, null);
g2d.dispose();
}
}
This is the 16x16 I am trying to draw
This is what my computer shows me
I have tried multiple ways to specify the size of the image, but Java seems to distort my image no matter what I do. Thank you in advance.

Java resize an image

I would like to display an image in an area in my Jframe but the image takes up much space.
I would like to take it fair precise dimensions.
How can I do this in Java
This is my simple code :
I am open to any proposal if I did not use the right method or the right class to instantiate the image.
import java.awt.*;
import javax.swing.*;
public class ExempleDeplace extends JFrame{
private JLabel myLabel;
public ExempleDeplace(){
setLayout(new FlowLayout());
setTitle("Fenetre, modele Duchi");
setSize(500,700);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel j = new JLabel(new ImageIcon("src/images/bateau.png"));
add(j);
setVisible(true);
}
public static void main (String[] args) {
ExempleDeplace c = new ExempleDeplace();
}
}
You can paint the image in a JPanel as the whole panel. Then whenever the panel is resized, the image will be resized along with it. Here's a quick-n-dirty runnable demo:
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class ImgFrame extends JFrame {
private static BufferedImage IMG;
static{
try {
IMG = ImageIO.read(new File("img/Original_Doge_meme.jpg")); //Replace with your image path
} catch (IOException e) {
e.printStackTrace();
}
}
public ImgFrame(){
add(new ImgPanel(), BorderLayout.CENTER);
setSize(500,700);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
class ImgPanel extends JPanel{
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(IMG, 0, 0, getWidth(), getHeight(), this);
}
}
public static void main(String[] args){
new ImgFrame();
}
}
It's probably cleaner to just resize the image. I highly recommend the image resizing utility methods provided by filthyrichclients.
I actually highly recommend the book as well, as it was one of the few books that actually demonstrated the power of Swing...
Once you have the code, you will want to call
createCompatibleImage(myImage, myWidth,myHeight);

Failing to draw Image to JFrame

first I want to apologize for any mistakes, I'm not speaking english well, I'm new to Java and I'm new to Stackoverflow. Please be kind!
I keep failing to draw a simple image to screen. I tried everything, but I keep failing and I'm getting more and more confused. Here's my Sourcecode:
package com.Animation;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import java.awt.Graphics2D;
import java.awt.Point;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
#SuppressWarnings("serial")
public class Class1 extends JFrame{
private BufferedImage backgroundImg;
public Class1(){
this.setTitle("Animation");
this.setSize(1080, 720);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
LoadContent();
}
public static void main(String[] args){
new Class1();
}
private void LoadContent()
{
try
{
URL backgroundImgUrl = this.getClass().getResource("Back.jpg");
backgroundImg = ImageIO.read(backgroundImgUrl);
}
catch (IOException ex) {
System.err.println("Fehler!");
}
}
public void Draw(Graphics2D g2d)
{
g2d.drawImage(backgroundImg, 0, 0, null);
}
}
So what happens is, that a JFrame window opens with nothing to see on it. I think that's beacuse the Draw() method doesn't get called. But when I add like "Draw(g2d);" somewhere, I keep getting a NullPointerException. The picture "Back.jpg" is located in the same package as the class. I'm using eClipse and the JRE JavaSE 1.7.
I really hope you can help me, im totally exhausted by all my tries to figure out what's the problem. It would be cool if you could write the correct code into the answers and explain what I've done wrong. Remember, I'm new to all this.
Thanks a lot!
There are a lot of ways to do that. Examples
1) JLabel. //Not recommended
Add the JLabel in your JFrame, then do label.setIcon(backgroundImg);
2) JPanel
Override the paint() method in JPanel(make sure you've added it to your JFrame).
#Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(backgroundImg, 0, 0, this);
}
Try this. Here I have set the image to a JPanel instead of directly setting it to JFrame.
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
/**
*
* #author Rumesh
*/
public class Test extends JFrame{
public static void main(String[] args) throws IOException {
JFrame frame = buildFrame();
final BufferedImage image = ImageIO.read(new File("1.jpg"));
JPanel pane = new JPanel() {
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
};
frame.add(pane);
}
private static JFrame buildFrame() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
return frame;
}
}
I don't know if this is what you're searching for:
ImageIcon image = new ImageIcon("src/media/Image.jpg");
JLabel lblImg = new JLabel("", image, JLabel.CENTER);
lblImg.setBounds(..., ..., ..., ...);
add(lblImg);
This way you'll add an image to a JLabel and than place it on the screen. I hope it helps in some way.

Using components in a JApplet that has a continually repainted JPanel

I'm having a major problem with this school assignment; lucky I started it early for once. We've been asked to make a children's math game using a JApplet. So far so good. I have managed to create a JPanel, which is then added to the JApplet and holds all the drawings (the JPanel contents are continually being redrawn). However, whenever I try to add a Swing component such as a JLabel to the JApplet content pane, it does not show or show signs of ever existing. I am completely new to JApplets so please don't be too harsh if it's obvious.
Below is the code:
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JApplet;
import javax.swing.JPanel;
import javax.swing.Timer;
public class CountingSheep extends JApplet
{
final int BOARDWIDTH = 800;
final int BOARDHEIGHT = 500;
final int SCREENWIDTH = 800;
final int SCREENHEIGHT = 800;
Dimension boardDim = new Dimension(BOARDWIDTH, BOARDHEIGHT);
Dimension screenDim = new Dimension(SCREENWIDTH, SCREENHEIGHT);
Graphics bufferGraphics;
Image offScreen;
Image backgroundImage;
Image[] sheepImage = new Image[2];
JPanel gameBoard = new JPanel(true);
List<Sheep> sheepArray = new ArrayList<>();
Timer myTimer;
public void init()
{
loadImages();
initScreen();
initBufferGraphics();
initBoard();
initTimer();
sheepArray.add(new Sheep(sheepImage));
myTimer.start();
}
private void loadImages()
{
sheepImage[0] = getImage(getDocumentBase(), "sheep.png");
sheepImage[1] = getImage(getDocumentBase(), "sheep2.png");
backgroundImage = getImage(getDocumentBase(), "bg.jpg");
}
private void initScreen()
{
setSize(800, 600);
setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
}
private void initBoard()
{
gameBoard.setPreferredSize(new Dimension(BOARDWIDTH, BOARDHEIGHT));
getContentPane().add(gameBoard);
}
private void initBufferGraphics()
{
offScreen = createImage(BOARDWIDTH, BOARDHEIGHT);
bufferGraphics = offScreen.getGraphics();
}
private void initTimer()
{
myTimer = new Timer(80, new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
timerTick(e);
}
});
}
private void timerTick(ActionEvent e)
{
repaint();
}
public void paint(Graphics g)
{
bufferGraphics.clearRect(0, 0, BOARDWIDTH, BOARDHEIGHT);
bufferGraphics.drawImage(backgroundImage, 0, 0, null);
drawSheepHerd();
moveSheepHerd();
gameBoard.getGraphics().drawImage(offScreen, 0, 0, this);
}
public void drawSheepHerd()
{
for (Sheep s : sheepArray)
{
s.draw(bufferGraphics);
}
}
public void moveSheepHerd()
{
for (Sheep s : sheepArray)
{
s.move();
}
}
}
Thanks in advance, hope you guys can figure it out because I'm stumped.
To summarize some of my recommendations:
Create your own ContentPane class that extends JPanel, that overrides paintComponent(...) and that draws your background image and shows the animation.
Call setContentPane(...) on the JApplet in the init method, passing in an object of this class.
Experiment with different layouts and positionings for the ContentPane.
Make sure that the very first line of the paintComponent(Graphics g) method is: super.paintComponent(g) so that your drawing will be reset each time it paints.
JPanels are opaque by default, and you should leave it as such since contentPanes must be opaque. If you add components on top of the contentPane and want to see the image behind the added components, you may have to make them non-opaque.

Categories