exception - How do I display an image on a frame using paintComponent -
this code:
package com.dani.game; import java.awt.*; import java.awt.image.bufferedimage; import javax.imageio.imageio; import javax.swing.*; import java.io.*; import java.util.*; public class game extends jframe { bufferedimage normal; public static void main(string[] args) { game game = new game(); } public game() { this.setdefaultcloseoperation(jframe.exit_on_close); try { normal = imageio.read(new file("c:\\imageone.jpg")); } catch (ioexception e) { e.printstacktrace(); } imagepanel graphics = new imagepanel(); this.add(graphics); this.setvisible(true); } public class imagepanel extends jpanel { public void paintcomponent(graphics g) { super.paint(g); g.drawimage(normal,normal.getwidth(), normal.getheight(), this); } } updated:
when try exception :
exception in thread "awt-eventqueue-0" java.lang.stackoverflowerror @ sun.awt.appcontext.get(unknown source) @ javax.swing.repaintmanager.currentmanager(unknown source) @ javax.swing.repaintmanager.currentmanager(unknown source) @ javax.swing.repaintmanager.currentmanager(unknown source) @ javax.swing.jcomponent.paint(unknown source) @ com.course.swing.headprac$drawing.paintcomponent(headprac.java:99) @ javax.swing.jcomponent.paint(unknown source) what doing wrong?
anyway, couse stackoverflow due calling loop between paint , paintcomponent. replace super.paint(g) super.paintcomponent(g) start.
its working form me anyway
package com.dani.game; 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 game extends jframe { bufferedimage normal; public static void main(string[] args) { game game = new game(); } public game() { this.setlayout(new borderlayout()); this.setdefaultcloseoperation(jframe.exit_on_close); try { normal = imageio.read(new file("d:\\providers.gif")); } catch (ioexception e) { e.printstacktrace(); } imagepanel graphics = new imagepanel(); this.add(graphics, borderlayout.center); this.setvisible(true); } public class imagepanel extends jpanel { public void paintcomponent(graphics g) { super.paintcomponent(g); g.drawimage(normal, 0, 0, normal.getwidth(), normal.getheight(), this); } } }
Comments
Post a Comment