-3

Help! How can I add image on my JFrame? This is my code

public class JavaApplication79 extends JFrame{

 ImageIcon icon = new ImageIcon("Downloads/splash.jpg");
 JLabel label = new JLabel(icon);

public JavaApplication79(){
    add(label);

    setLayout(null);
    setSize(900,500);
    setLocationRelativeTo(null);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public static void main(String args[]){
JavaApplication79 show = new JavaApplication79();
show.setVisible(true);
}
 }
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • 4
    Possible duplicate of [How to add an image to a JPanel?](http://stackoverflow.com/questions/299495/how-to-add-an-image-to-a-jpanel) – Eli Sadoff Nov 27 '16 at 04:59
  • *`setLayout(null);`* Uh-huh. Add a `LineBorder` to the `JLabel` – Andrew Thompson Nov 27 '16 at 05:22
  • 1
    1) A single blank line of white space in source code is all that is *ever* needed. Blank lines after `{` or before `}` are also typically redundant. 2) Use a logical and consistent form of indenting code lines and blocks. The indentation is intended to make the flow of the code easier to follow! – Andrew Thompson Nov 27 '16 at 05:24

1 Answers1

1

The problems start with the null layout. Because there is no layout to set the component size to it's preferred size, or any other size, the panel takes its default size of 0 x 0 pixels.


  • For 'top left' of frame I'd recommend FlowLayout.
  • For 'center' of frame - GridBagLayout is easy.
  • For 'centered & stretched' to fill the frame, GridLayout.

Learn about layouts in the Laying Out Components Within a Container lesson of the tutorial.

But an extra tip about combining layouts for different effects in different parts of the GUI. Use layout managers, or combinations of them along with layout padding and borders for white space.

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433