Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Display a JPEG  RSS feed

 
Pingili Vishwanath
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Iam trying to display a JPEG image in JFrame. The following code is just displaying a frame , but not the JPEG image (in this case, it is nath1.jpeg).

Can someone give the solution to this problem? Please try with your own JPEG and change the file name in this program. Thanks in advance.

------------------------------------------------

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Noname2
{
JFrame frame;

public static void main(String[] args)
{
Vish1Gui gui = new Vish1Gui();
gui.go();
}

public void go()
{
frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

MyDrawPanel drawPanel = new MyDrawPanel();

frame.getContentPane().add(drawPanel);
frame.setSize(300,300);
frame.setVisible(true);
}
}

class MyDrawPanel extends JPanel
{
public void paintComponent(Graphics g)
{
Image image = new ImageIcon("nath1.jpeg").getImage();
g.drawImage(image,10,20,this);
}
}

------------------------------------------------------
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
never, ever 'get' the image in paintComponent()
the method is called numerous times.

the swing faq has an example of a JPanel with background image

http://faq.javaranch.com/view?BackgroundImageOnJPanel
 
Malith Yapa
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's an easy way of doing you stuff..

Create a class which extends the jPanel class. Override it's paint method and draw the image there.(Using what you have already done) Then in your jFrame class use the method like this :-

Assume that the extended Jpanel class you created was exjpanel then in the jFrame type the code



That should work..
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!