image doesnt shows on JLabel when click on next button, using java Swing -
i trying make small program shows pic on jlabel when user click on next button.the problem when click on next button shows nothing.but if resize frame shows pics directory. instead of 1 picture @ time. please excuse english. here code.
import java.awt.*; import javax.swing.*; import java.awt.event.*; import javax.imageio.imageio; import java.io.*; import java.awt.image.bufferedimage; class test { public static void main(string args[]) { frame f = new frame(); f.gui(); f.actions(); } } class frame { bufferedimage file; file img; imageicon icon; jlabel image; jframe frame; jpanel panel; string[] path = { "juice.jpg", "gal.jpg", "truck.jpg", "drive.jpg" }; jbutton next = new jbutton("next"); jbutton pre = new jbutton("prevoius"); jtextfield field = new jtextfield(10); static int num = 0; public void gui() { frame = new jframe("pic gallery"); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.setvisible(true); flowlayout flow = new flowlayout(); frame.setlayout(flow); panel = new jpanel(); panel.setlayout(new boxlayout(panel, boxlayout.line_axis)); panel.add(next); panel.add(pre); panel.add(field); jlabel piclabel = new jlabel(); frame.getcontentpane().add(panel); } void actions() { next.addactionlistener(new actionlistener() { public void actionperformed(actionevent e) { img = new file(path[num]); system.out.println(num); try { file = imageio.read(img); icon = new imageicon(file); image = new jlabel("", icon, jlabel.center); image.setvisible(true); frame.getcontentpane().add(image); } catch (ioexception g) { } if (num < path.length - 1) { num++; field.settext(num + ""); } else { num = 0; } } }); } }
add frame.revalidate()
, frame.repaint()
after frame.getcontentpane().add(image);
swing lazy when comes performing updates layout hierarchy, thing, imagine adding few dozen components , having entire component hierarchy been updated each one.
so, instead, need update container manually when you've made changes
added suggested . shows next image on frame along prevous image. wants 1 image @ time
then remove first image, or better yet, instead of creating new jlabel
each time, create single jlabel
, change it's icon
property, should invalidate container automatically
Comments
Post a Comment