java - Why doesn't paintComponent(Graphics g) of JPanel run? -
java - Why doesn't paintComponent(Graphics g) of JPanel run? -
during experience before, paintcomponent(graphics g) of panel run when initial , can create repaint calling repaint() method. demo below doesn't work experience. what's wrong it?
import java.awt.borderlayout; import java.awt.dimension; import java.awt.graphics; import java.awt.image.bufferedimage; import java.io.file; import java.io.ioexception; import javax.imageio.imageio; import javax.swing.borderfactory; import javax.swing.imageicon; import javax.swing.jframe; import javax.swing.jlabel; import javax.swing.jpanel; import javax.swing.jscrollpane; public class backgroundtest { public static void main(string[] args) { backgroundtest backgroundtest = new backgroundtest(); seek { backgroundtest.createui(); } grab (ioexception e) { // todo auto-generated grab block e.printstacktrace(); } } public void createui() throws ioexception{ jframe frame = new jframe("background test"); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setresizable(true); jpanel mainpanel = new jpanel(); jlabel backgroundlabel = new jlabel(new imageicon("background.png")); jpanel imagepanel = new imagepanel(); imagepanel.setpreferredsize(new dimension(626, 434)); // it's size of house.png jscrollpane scrollpane = new jscrollpane(imagepanel); backgroundlabel.add(scrollpane,borderlayout.center); mainpanel.add(backgroundlabel); frame.add(mainpanel,borderlayout.center); frame.getcontentpane().add(backgroundlabel,borderlayout.center); frame.pack(); frame.setlocationrelativeto(null); frame.setvisible(true); } @suppresswarnings("serial") class imagepanel extends jpanel { protected void paintcomponent(graphics g) { system.out.println("i'm not run"); super.paintcomponent(g); bufferedimage image = null; seek { image = imageio.read(new file("house.png")); } grab (ioexception e) { // todo auto-generated grab block e.printstacktrace(); } g.drawimage(image, 0, 0, null); } } }
jlabel
has no layout manager installed default, meaning add together never resized , hence never painted, swing smart way
try using like...
backgroundlabel.setlayout(new borderlayout());
don't load images within paintcomponent
method, paints may occur , within quick succession each other, slows downwards paint process slow downwards everything
you should avoid using setpreferredsize
, instead, allow component decided based on knows, example
class imagepanel extends jpanel { private bufferedimage image = null; public imagepanel() { seek { image = imageio.read(new file("house.png")); } grab (ioexception e) { // todo auto-generated grab block e.printstacktrace(); } } @override public dimension getpreferredsize() { homecoming image == null ? super.getpreferredsize() : new dimension(image.getwidth(), image.getheight()); } protected void paintcomponent(graphics g) { super.paintcomponent(g); if (image != null) { g.drawimage(image, 0, 0, null); } } }
java swing awt
Comments
Post a Comment