I want to display an image inside a panel. So I pass the path of the image to this method, open image file and pass it to the method of a private class dedicated to draw image inside the panel. The problem is the panel remains empty all the time and doesn't display anything.
Here is the code:
JPanel ImagePane; // I want to add image to this
public void getImagePath(String Path)
{
BufferedImage image = null;
try
{
image=ImageIO.read(new File(Path));
}
catch (IOException e)
{
e.printStackTrace();
}
DisplayImage display= new DisplayImage();
display.getImage(image);
}
private class DisplayImage extends JPanel
{
private BufferedImage image=null;
public void getImage(BufferedImage im)
{
image=im;
repaint();
}
public void paintComponents(Graphics g)
{
g.drawImage(image, 0, 0, image.getWidth() /2, image.getHeight()/2,ImagePane);
}
}
What am I missing?
paintComponents is a method of the Container which is used to paint each of the components in the container. Instead you need paintComponent to paint this single component.
Change your
public void paintComponents(Graphics g)
method to
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, image.getWidth() /2, image.getHeight()/2,ImagePane);
}
Notice the use of the #Override annotation to help with method signature checking.
Also calling
super.paintComponent(g);
will update child components.
In your method getImagePath you don't appear to add the DisplayImage to any container. Instead you create a local DisplayImage, but don't use it.
You have to override paintComponent
protected void paintComponent(Graphics g)
But in your code you are creating public void paintComponents(Graphics g) which is not correct
There's the use of #Override annotation. If you make it a practice to use it whenever you're overriding a method, this issue can be resolved at compile-time. You need to use this:
#Override
public void paintComponent(Graphics g)
Related
Main class:
public Main() {
Frame f = new Frame();
final Panel p = f.p;
final Player player = new Player();
Timer t = new Timer(UPDATE_PERIOD, new ActionListener() {
public void actionPerformed(ActionEvent e) {
Graphics g = p.getGraphics();
p.render(g);
player.tick();
player.render(g);
g.dispose();
}
});
t.start();
}
Player render method:
public void render(Graphics g) {
g.drawImage(Images.get("player"), x, y, null);
}
The problem is, that all previous drawn images are still there. Example (when I change the drawn image's x or y):
To draw in Swing, you should not be getting the Graphics object directly from the JPanel. Instead, override the paintComponent method and use the parameter Graphics object to perform your custom drawing, with a call to the parent method to erase previous painting
#Override
public void paintComponent(Graphics g){
super.paintComponent(g);
//custom painting goes here
}
If you wish to trigger a repaint, use the method by that name on the JPanel:
p.repaint();
Rather than doing custom rendering your your timer, you should really be doing all your painting in your paintComponent method. Something like:
public void actionPerformed(ActionEvent e) {
player.tick();
p.repaint();
}
And then re-render the player and the background in paintComponent()
Painting like you currently are runs into issues when you resize the panel, etc
Try calling 'p.repaint()' in your ActionListener once you have changed the position of the Graphic.
I want to load an image to JPanel. The images that are going to be drawn are images saved from this JPanel.
For example i have this picture that has been capture from the JPanel and later i want to load that image to the same JPanel.
I have tried this but it does not work. This piece of code is inside a class that extends JPanel. Any suggestions?
public void load(String path) throws IOException {
BufferedImage img = ImageIO.read(new File(path));
Graphics2D g2d = img.createGraphics();
g2d.drawImage(img, 0, 0, null);
this.repaint();
}
You draw the image back to itself (?) using a Graphics object derived from the Image itself. Instead store the image to a field, not a local variable, and draw that image within the JPanel's paintComponent method. Most important, have a look at the Swing graphics tutorials
private BufferedImage img;
public void load(String path) throws IOException {
img = ImageIO.read(new File(path));
this.repaint();
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (img != null) {
g.drawImage(img, 0, 0, null);
}
}
you can do that by an override
public void paintComponent(Graphics g) {...} for javax.swing components
and public void paint(Graphics g) for java.awt components
I'm not that familiar with Java and I'm a little clueless about my current problem.
I'm trying to draw an Image within a separate class of my Main JFrame, but it
always draw just a little piece of the picture (maybe 10x10px).
(A test with a Label worked)
Maybe I didn't used the g.drawImage method correct, or the JPanel don't have enough space??
MainWindow:
public class Deconvolutioner extends JFrame {
Draw z;
Picturearea picturearea;
class Draw extends JPanel {
public void paint(Graphics g) {
}
}
public Deconvolutioner() {
setTitle("Deconvolutioner");
setLocation(30,1);
setSize(1300,735);
super.setFont(new Font("Arial",Font.BOLD,11));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FlowLayout flow = new FlowLayout(FlowLayout.CENTER);
this.setLayout(flow);
picturearea = new Picturearea();
this.add(picturearea);
add(z = new Draw());
setVisible(true);
}
class Open implements ActionListener {
public void actionPerformed(ActionEvent e) {
JFileChooser fileOpen = new JFileChooser();
FileFilter filter = new FileNameExtensionFilter("png & jpg files", "png",
"jpg");
fileOpen.addChoosableFileFilter(filter);
int returnVal = fileOpen.showDialog(null, "Open file");
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
String path = fileOpen.getSelectedFile().getPath();
URL url = new File(path).toURI().toURL();
BufferedImage img = ImageIO.read(url);
picturearea.setPicture(img);
} catch (IOException ex) {
System.err.println("Some IOException accured (set the right path?): ");
System.err.println(ex.getMessage());
}
} else {
}
repaint();
}
}
And the separate class:
public class Picturearea extends JPanel {
public BufferedImage image;
Draw z;
public Picturearea() {
add(z = new Draw());
setVisible(true);
}
class Draw extends JPanel {
#Override
public void paint(Graphics g) {
g.drawImage(image, 0, 0, this);
}
}
public void setPicture(BufferedImage picture) {
try {
image = picture;
} catch (Exception e) {
System.err.println("Some IOException accured (did you set the right path?): ");
System.err.println(e.getMessage());
}
repaint();
}
}
I'm grateful for every help.
thanks for your time.
You are using FlowLayout for JFrame's contentPane's layout. FlowLayout obeys component's preferredSize. Try setting preferredSize of your pictureArea by pictureArea.setPreferredSize(Dimension) or overriding getPreferredSize(Dimension) function in PictureArea class.
you are using paint(Graphics g) for custom painting:
#Override
public void paint(Graphics g) {
g.drawImage(image, 0, 0, this);
}
Do not override paint() for custom painting override paintComponent(Graphics g) instead. And You may need to scale your image to fit in the size of the JPanel. you can use g.drawImage(x, y, width, height, observer) function if you need to scale your image.
#Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, this);
}
I created a component to display Image in jPanel.But its not showing the image during design time.how to show Image on design time?
public class JImagePanel extends JPanel {
private BufferedImage _img=null;
public JImagePanel() {
super();
}
public void setImage(URL img) {
try{
this._img = ImageIO.read(img);
validate();
repaint();
}catch(Exception err){
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if(this._img!=null)
g.drawImage(_img, 0, 0, getWidth(), getHeight(), this);
}
}
if you want to display Icon/ImageIcon only, then better would be look for JLabel as painting background by using paintComponent(Graphics g)
I have a quick question about Java. I'm sorry if this question is really basic, but I'm a beginner Java programmer :D
I want to render a 2d image in a window, but I can't figure it out. I've looked at the graphics API here:
http://download.oracle.com/javase/1.4.2/docs/api/java/awt/Graphics.html
and the only method I could find that might work is drawImage().
It wasn't working for me, though, but maybe it has to do with the ImageObserver Observer parameter? I just put null for that following some tutorial I found somewhere, but I still get a compile error:
Here is my paint method:
public void paint(Graphics g)
{
Image img1 = Toolkit.getDefaultToolkit().getImage("theImage.png");
g.drawImage(img1, 100, 100, null);
} // public void paint(Graphics g)
and here are the methods that call it:
public static void main(String[] args)
{
MyGame game = new MyGame();
game.setVisible(true);
game.play();
} // public static void main(String[] args)
/** The play method is where the main game loop resides.
*/
public void play()
{
boolean playing = true;
//Graphics g = new Graphics();
while (playing)
{
paint();
}
} // public void play()
The thing is when I call paint in the while loop, I get this error:
paints(java.awt.Graphics) in MyGame cannot be applied to ()
What does that mean? How can I fix it so I can successfully render a 2d image?
Thanks in advance :D
Instead of paint(); use repaint();
You should be overriding paintComponent(Graphics g). Also, as #TotalFrickinRockstarFromMars suggested, you should be invoking repaint().
You overrid the paintComponent(Graphics g)
class Game extends JComponent { // Your game class
Image img = null;
public Game() {
img = getImage("/theImage.png");
}
private Image getImage(String imageUrl) {
try {
return ImageIO.read(getClass().getResource(imageUrl));
} catch (IOException exp) {}
return null;
}
paintComponent(Graphics g) {
g.drawImage(img, 100, 100, null);
}
}