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
Related
It is very simple program and i have tried my best but the JPanel doesn't come up with a background image. I just want a simple background image on my panel.
Here is my code:
import javax.swing.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.*;
import java.awt.Graphics;
class PanelEx extends JPanel
{
BufferedImage img;
PanelEx()
{
try
{
img = ImageIO.read(new File("C:/Users/Pictures/s_4261.jpg"));
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
public void printComponent(Graphics g)
{
g.drawImage(img,0,0,null);
}
}
class JPanelEx2 extends JFrame
{
PanelEx pe;
public static void main(String args[])
{
new JPanelEx2();
}
JPanelEx2()
{
pe = new PanelEx();
add(pe);
setTitle("JPanel Title");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setSize(320,240);
setVisible(true);
}
}
Thanks in advance
Replace
public void printComponent(Graphics g) {
with
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
Don't use a JPanel. Just use a JLabel with an Icon then you don't need custom code.
See Background Panel for more information as well as a solution that will paint the image on a JPanel with 3 different painting options:
scaled
tiled
actual
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);
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
This is a really general question, but how should I add an animated background for a JPanel. I want the background to be behind all the panel's components and graphics. Right now, I have two separate classes (one for the main panel and the other for the background). The background class uses repaint() to animate a grid moving across the screen. I've tried to make the main panel background transparent, but that hasn't gotten me anywhere.
Even more info:
My main panel is part of a CardLayout and it has many different classes in it. So when I'm adding my main panel to my main frame, I'm doing frame.getContentPane().add(cards, BorderLayout.CENTER)
cards is a JPanel which acts as a container for the mainpanel and all the panels inside main panel.
Can anybody help me out in getting a panel animated background?
You can use Toolkit.getImage() to load animated image and then draw the image in container's paintComponent. Make sure the ImageObserver is set (not null) in order to update animation frames properly. For details how image is loaded, observed and updated see How Images are Loaded appendix in Java AWT Reference.
Here is a simple example:
import java.awt.*;
import javax.swing.*;
import java.net.URL;
class AnimatedPanelDemo {
static class ImagePanel extends JPanel {
private Image image;
ImagePanel(Image image) {
this.image = image;
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image,0,0,getWidth(),getHeight(),this);
}
}
private static void createAndShowUI() {
try {
JFrame frame = new JFrame("Image");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
Image image = Toolkit.getDefaultToolkit().getImage(new URL(
"http://duke.kenai.com/iconSized/duke.running.gif"));
ImagePanel imagePanel = new ImagePanel(image);
imagePanel.add(new JLabel("Some label"));
frame.add(imagePanel);
frame.setSize(100, 100);
frame.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
Well, this is my first answer on stackoverflow.
Will try to help with my learning curve with this complex AWT and Swift API.
Below there's the contructor that extends JFrame
package xpto;
import java.awt.Dimension;
import java.awt.GraphicsConfiguration;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.event.WindowStateListener;
import java.awt.image.ImageObserver;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import sun.java2d.SunGraphicsEnvironment;
import java.awt.Graphics;
import java.awt.Graphics2D;
public class FrameLuckyRaffle extends JFrame {
/**
*
*/
private JLabel backgroundLabel;
private ImageIcon imageIcon;
private Image bgImage;
/**
* Constructor of this frame.
*/
public FrameLuckyRaffle(String background, final String dbname) {
try {
setTitle("Lucky Raffle of "+ dbname);
GraphicsConfiguration config = this.getGraphicsConfiguration();
Rectangle usableBounds = SunGraphicsEnvironment.
getUsableBounds(config.getDevice());
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setBounds(100, 100, (int)(usableBounds.getWidth()*0.8),
(int)(usableBounds.getHeight()*0.8));
setMinimumSize(new Dimension(1024, 700));
setResizable(true);
setDefaultLookAndFeelDecorated(true);
backgroundLabel = new JLabel() {
public void paintComponent(Graphics g) {
// alternative --> g.drawImage(bgImage, 0, 0, null);
// I prefer to control the new ImageObserver parameter as bellow
g.drawImage(bgImage, 0, 0, new ImageObserver() {
#Override
public boolean imageUpdate(Image img, int infoflags,
int x, int y, int width, int height) {
img.getScaledInstance(getWidth(),getHeight(),
Image.SCALE_FAST);
return true;
}
});
// this is used to have easier control on
// image manipulation on my application
Graphics2D g2d = (Graphics2D)g;
super.paintComponent(g2d);
revalidate();
repaint();
}
};
backgroundLabel.setBounds(0, 0, 0, 0);
// this is necessary if you want more child
// components to be visible on the JFrame afterwards
backgroundLabel.setOpaque(false);
setContentPane(backgroundLabel);
addWindowListener(new WindowListener() {
#Override
public void windowOpened(WindowEvent e) {
// Set Frame Background
imageIcon = new ImageIcon(Toolkit.getDefaultToolkit().
createImage(FrameBusinessPure.class.getResource(background)));
bgImage = imageIcon.getImage().
getScaledInstance(getWidth(),getHeight(), Image.SCALE_FAST);
}
// Even after closing the window, JVM didn't Garbage Collected the instanced
// objects, for some reason. Forcing the objects to null helped on that.
#Override
public void windowClosed(WindowEvent e) {
backgroundLabel = null;
imageIcon = null;
bgImage = null;
System.gc();
}
});
addWindowStateListener(new WindowStateListener() {
#Override
public void windowStateChanged(WindowEvent e) {
// if you flush the object on runtime you will surpass the
// memory leak on using GIFs and most complex graphics
bgImage.flush();
bgImage = imageIcon.getImage().
getScaledInstance(getWidth(),getHeight(), Image.SCALE_FAST);
}
});
addMouseMotionListener(new MouseMotionListener() {
#Override
public void mouseDragged(MouseEvent e) {
// if you flush the object on runtime you will surpass the
// memory leak on using GIFs and most complex graphics
bgImage.flush();
bgImage = imageIcon.getImage().
getScaledInstance(getWidth(),getHeight(), Image.SCALE_FAST);
});
}catch (Exception e) {
e.printStackTrace();
}
}
}
Feel free to learn more on below link
https://www.oracle.com/java/technologies/painting.html
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.