I am coding a gui and I wanted to use embedde some pictures, but before embedding it in my main program I wrote that code to test it:
public class guikopie extends javax.swing.JFrame{
public guikopie() {
a = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
a.setIcon(new javax.swing.ImageIcon("C:\\Users\\Public\\Pictures\\Sample Pictures\\Tulpen.jpg"));
add(a);//here i add it to the jlabel
pack();
}
public static void main(String args[]){
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new guikopie().setVisible(true);
}
});
}
private javax.swing.JLabel a;
}
My question is: Why does this code do not display the picture?
I think people may hate me for repeating this :P:
GuikopieAlso depending on what the background is being used for i.e if its a logo that will be added to a specific location on the
JPanelthen using aJLabelis fine, however, if its being used as a background it is not; because it will moved around as more components are being added, thus we should not add the background as a component rather we paint the background on the component.As for your question:
your code works perfect for me thus the location of your picture must be incorrect.
I did a short example showing how to add a
ImagetoJPanelbackground and then addJPaneltoJFrame, it also includes classImgUtilsfor resizing picture:Alternatively you may want to resize using Image#getScaledInstance(int width,int height,int hints), but this has its perils, the main problem being: