I want to have an ImageIcon in a JLabel that i will be able to update from another method. But I can't figure out a way to be able to create a static JLabel(so as to be able to acccess it from another method) and also instaiate it as a Jlabel that contains an imageIcon - is there another method other than JLabel label = new JLabel(imgIcon) to create a label with an imageIcon? tried to use the setIcon method without the label being instatiated the way it is above but it gave a null pointer exception. Thanks in adavance for any help.
views:
455answers:
2Don't make the JLabel static - instead define it outside of other methods but still in your class.
public class Test {
private JLabel label = new JLabel(new ImageIcon(/*your icon*/));
}
If you need to access it from another class, create an accessor method:
public JLabel getLabel() {
return label;
}
I havent been able to get AlbertoPL way to work so I have make a short example program that brings up the same null pointer error when run, if you just change the images to any jpg of ur own choice u will b able to see the problem and hopefully will be able to help me out. AlbertoPL what you are telling me probably works just I am not understanding it vey well. UI have also included the methods used to resize the bufferedImage and load the image, incase the error is oming from there, but the nullpointer says it is coming from the line
picPanel.add(labelPicPanel);
Thanks very much in advance for any help.
the example code is,
public class test {
static JPanel picPanel;
static JLabel labelPicPanel = new JLabel(new ImageIcon("C:/Documents and Settings/Admin/My Documents/My Pictures/pi.jpg"));
public static void test() {
String ref = "C:/temp/new00000001.jpg";
BufferedImage loadImg = loadImage(ref);
ImageIcon imgIcon = new ImageIcon(loadImg);
labelPicPanel.setIcon(imgIcon);
picPanel.add(labelPicPanel);
picPanel.setPreferredSize(new Dimension(1120, 620));
JFrame frame = new JFrame("Frame");
frame.add(picPanel);
frame.pack();
frame.setVisible(true);
}
public static BufferedImage loadImage(String ref) {
BufferedImage bimg = null;
try {
bimg = javax.imageio.ImageIO.read(new File(ref));
} catch (Exception e) {
e.printStackTrace();
}
BufferedImage bimg2 = resize(bimg,1120,620);
return bimg2;
}
public static BufferedImage resize(BufferedImage img, int newW, int newH) {
int w = img.getWidth();
int h = img.getHeight();
BufferedImage dimg = dimg = new BufferedImage(newW, newH, img.getType());
Graphics2D g = dimg.createGraphics();
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(img, 0, 0, newW, newH, 0, 0, w, h, null);
g.dispose();
return dimg;
}
public static void main(String args[]){
test();
}
}