Image not drawn in JPanel - java

This is the code i tried to use to paint an image on screen (location of the image is correct), the code runs but nothing is drawn on the screen. My program's getFile() and paintComponent() method:
BufferedImage image;
public void getFile() throws IOException{
image = ImageIO.read(new File("grass.png"));
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
}

You do realise that you never create an instance of DrawImage nor do you actually add it to anything that could display it
public class DrawImage extends JPanel
{
BufferedImage image;
public DrawImage() throws IOException {
getFile();
}
public void getFile() throws IOException
{
image = ImageIO.read(new File("grass.png"));
}
//...
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DrawImage pane = new DrawImage();
JFrame frame = new JFrame();
frame.add(pane);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
} catch (IOException exp) {
exp.printStackTrace();
}
}
});
}

Instead of JPanel pane = new JPanel(), you should do DrawImage pane = new DrawImage() and before you do frame.add(pane) call pane.getFile().
Since you always need to call getFile() before drawing the DrawImage, why don't you put it into a constructor of the DrawImage class?

First you didn't use your class that draw the image (DrawImage)
in this line JPanel pane = new JPanel(); so you must change it to DrawImage pane = new DrawImage();
second issue you didn't invoke getFile() method to initialize image object so either use as I mentioned below or invoke this method as your write in class drawImage constructor.
public class DrawImage extends JPanel{
BufferedImage image;
public Image getFile()
{
try {
image = ImageIO.read(new File("grass.png"));
return image;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
System.out.println(image);
g.drawImage(getFile(), 0, 100, null);
}
public static void main(String[] args)
{
DrawImage pane = new DrawImage();
JFrame frame = new JFrame();
frame.add(pane);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(400, 400);
frame.setVisible(true);
}
}

Related

How draw oval image in JLabel

I want to draw a oval image in a JLabel, using Graphics. This is my code, but a dont know about Graphics.
class imagePanel extends JLabel {
//private PlanarImage image;
private BufferedImage buffImage = null;
private void drawFingerImage(int nWidth, int nHeight, byte[] buff) {
buffImage = new BufferedImage(nWidth, nHeight, BufferedImage.TYPE_BYTE_GRAY);
buffImage.getRaster().setDataElements(0, 0, nWidth, nHeight, buff);
Graphics g = buffImage.createGraphics();
g.drawImage(buffImage, 0, 0, 140, 150, null);
g.dispose();
repaint();
}
public void paintComponent(Graphics g) {
g.drawImage(buffImage, 0, 0, this);
}
}
I have this
you need the help of setClip() method as mentioned here and here.
when it comes to code it should look like this
public class OvalImageLabel extends JLabel {
private Image image;
public OvalImageLabel(URL imageUrl) throws IOException {
image = ImageIO.read(imageUrl);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setClip(new java.awt.geom.Ellipse2D.Float(0f,0f, getWidth(),getHeight()/2));
g.drawImage(image, 0, 0, this);
}
}
and a running application that using this class
public class UsageExample extends JPanel {
public UsageExample() {
super(new BorderLayout());
OvalImageLabel l;
try {
l = new OvalImageLabel(new File("/path/to/image.png").toURI().toURL());
} catch (Exception e) {
e.printStackTrace();
return;
}
add(l, BorderLayout.CENTER);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame();
frame.setContentPane(new UsageExample());
frame.setSize(200, 200);
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}

Function: Image in a JFrame

I'm trying to right a function that creates a JFrame that contains an image. Problem is I only get an empty JFrame (no errors). Is there a better way to do this?
Here is the class that contains the function:
public class Play extends JFrame
{
protected static ImageIcon icon = new ImageIcon("C:\\Users\\Fadil\\Desktop\\Coding\\civii\\earth.jpg");
protected static JLabel label = new JLabel(icon);
protected static JFrame f = new JFrame("Age Of")
public static void PlayStart()
{
f.getContentPane().add(label);
f.repaint();
f.setVisible(true);
}
}
simply do the following
1- create Panel class and use media tool kit to get image in your class path lie this
class P extends JPanel {
Image bg = null;
P() {
MediaTracker mt = new MediaTracker(this);
bg = Toolkit.getDefaultToolkit().getImage("yourimage");
mt.addImage(bg, 0);
try {
mt.waitForAll();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int imwidth = bgimage.getWidth(null);
int imheight = bgimage.getHeight(null);
g.drawImage(bg, 1, 1, null);
}
}
2- add the panel to your frame to the frame
public class JF extendts JFrame{
public JF(){
add(new P()) ;
sitSize(300,200) ;
}
}

How to use command arguments in paintComponent method?

I am currently trying to create a Java GUI program that generates images based on the arguments given in the terminal. If I get the argument in the command line java Draw Image1 for example, I want to draw my image 1 and etc. for the others. How can one take a command argument and use it in paintComponent? Here's a sample of what I am trying to do below:
import javax.swing.*;
import java.awt.*;
public class Draw extends JPanel
{
public Draw()
{
this.setSize(800,800);
JPanel drawing = new JPanel();
this.add(drawing);
this.setVisible(true);
}
protected void paintComponent(Graphics g)
{
if (args[0].equals("Image1")) // won't work
{
super.paintComponent(g);
Image myImage = Toolkit.getDefaultToolkit().getImage("image/myimage.jpg");
g.drawImage(myImage, 0, 0, this);
}
else
{
// draw image 2
}
}
public static void main(String[] args)
{
// create new Jframe
JFrame frame = new JFrame("Draw");
frame.add(new Draw());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(500,500);
frame.setVisible(true);
}
}
Change this:
frame.add(new Draw());
to this:
frame.add(new Draw(args));
And then have your constructor accept a String array parameter and use it to set a class field.
public class Draw extends JPanel
{
private String[] params
public Draw(String params)
{
this.params = params;
this.setSize(800,800); // this generally should be avoided
JPanel drawing = new JPanel();
this.add(drawing);
this.setVisible(true);
}
protected void paintComponent(Graphics g)
{
super.paintComponent(g); // this should be out of the if block
if (params != null && params.length > 0 && params[0].equals("Image1")) {
// ..... etc
Edit: Andrew is right and I did not read your code carefully. Read your image in the constructor and use it in the image in the paintCompnent method
e.g.,
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
#SuppressWarnings("serial")
public class Draw extends JPanel {
private static final int PREF_W = 800;
private static final int PREF_H = PREF_W;
private BufferedImage image;
public Draw(String[] params) throws IOException {
if (params != null && params.length > 0) {
image = ImageIO.read(new File(params[0]));
}
// this.setSize(800,800);
JPanel drawing = new JPanel();
drawing.setOpaque(false); // may need this
this.add(drawing);
this.setVisible(true);
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
g.drawImage(image, 0, 0, null);
} else {
}
}
#Override
public Dimension getPreferredSize() {
if (isPreferredSizeSet()) {
return super.getPreferredSize();
}
// not sure if you want to size it to the image or not
if (image != null) {
int w = image.getWidth();
int h = image.getHeight();
return new Dimension(w, h);
} else {
return new Dimension(PREF_W, PREF_H);
}
}
public static void main(String[] args) {
// create new Jframe
JFrame frame = new JFrame("Draw");
try {
frame.add(new Draw(args));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// frame.setSize(500,500);
frame.pack();
frame.setVisible(true);
} catch (IOException e) {
e.printStackTrace();
}
}
}

Add an Background image to a Panel

I have a JPanel, and i want to add an image as its background. How can i do that ?
frame = new JFrame("Some frame");
panel1 = new JPanel();
panel1.setBorder(new EmptyBorder(5, 5, 5, 5));
// NEED TO ADD AN IMAGE TO THIS PANEL
panel1.setLayout(cardlayout);
frame.getContentPane().add(panel1);
frame.setLocationByPlatform(true);
frame.setVisible(true);
I need to add an image to the panel and how can i do it ?
UPDATE 1
panel1 = new JPanel()
{
private static final long serialVersionUID = 1L;
#Override
public void paintComponent(Graphics g)
{
g.drawImage(Toolkit.getDefaultToolkit().createImage("1.jpg"), 0, 0, null);
}
};
You need to override the method paintComponent(Graphics g) of JPanel and use drawImage() on the Graphics object g as in this example.
Also, check these two examples by #trashgod:
example.
example.
You have a resource location problem.
Toolkit#createImage may return an empty image if the resource can not be found.
I suggest you use the ImageIO API instead, it supports a wider range of image formats, but will also throw an exception if the image is not found or can not be loaded.
How you load the image will also depend on where the image is.
If the image exists on the file system, you can simply use a File object reference, if the image is an embedded resource (within you application), you will need to use Class#getResource to obtain a URL to it.
public class TestGraphics {
public static void main(String[] args) {
new TestGraphics();
}
public TestGraphics() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(new PaintTest());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class PaintTest extends JPanel {
private BufferedImage image;
public PaintTest() {
setLayout(new BorderLayout());
try {
// Use this if the image exists within the file system
image = ImageIO.read(new File("/path/to/image/imageName.png"));
// Use this if the image is an embedded resource
// image = ImageIO.read(getClass().getResource("/path/to/resource/imageName.png"));
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public Dimension getPreferredSize() {
return image == null ? super.getPreferredSize() : new Dimension (image.getWidth(), image.getHeight());
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (image != null) {
int x = (getWidth() - image.getWidth()) / 2;
int y = (getHeight()- image.getHeight()) / 2;
g.drawImage(image, x, y, this);
}
}
}
}

drawImage() with using BufferedImage doesn't draw

import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
public class Main
{
JFrame jf;
Main()
{
jf=new JFrame();
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(new MyCanvas());
jf.pack();
jf.setVisible(true);
}
public static void main(String[] args)
{
MyCanvas.img=Toolkit.getDefaultToolkit().createImage("1.jpg");
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new Main();
}
});
}
}
class MyCanvas extends JComponent
{
static Image img;
BufferedImage bi;
MyCanvas()
{
setPreferredSize(new Dimension(200,200));
bi=new BufferedImage(200,200,BufferedImage.TYPE_INT_ARGB);
Graphics g=bi.getGraphics();
for (int i=0;i<10;i++)
for (int j=0;j<10;j++)
g.drawImage(img,i*20,j*20,20,20,this);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawImage(bi,0,0,this);
//g.drawImage(img,0,0,this);
}
}
If I uncomment line g.drawImage(img,0,0,this); I get my image on window. But with this code I see empty window. It is easy to understand that g.drawImage(img,i*20,j*20,20,20,this); in loop doesn't draw but what is problem?
edited out the unrelated stuff I did for future readers to find the answer easier. In java i've always had to use getResource or getResourceAsStream to ensure the file loaded from the right directory correctly.
class MyCanvas extends JComponent
{
public static Image loadImage(String s)
{
try
{
return ImageIO.read(Main.class.getResource(s));
}
catch (Exception ex)
{
ex.printStackTrace();
return null;
}
}
}
1) put BufferedImage as Icon to the JLabel example here
2) your paintComponent in CustomCanvas could be
class MyCanvas extends JComponent {
private static final long serialVersionUID = 1L;
#Override
public Dimension getMinimumSize() {
return new Dimension(150, 150);
}
#Override
public Dimension getPreferredSize() {
return new Dimension(300, 300);
}
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(bi,0,0,this);
}
}

Categories