jframe - how to import image to JLabel? -


here code should display image , button below it

jframe frame = new jframe("frame title"); frame.getcontentpane().setlayout(new gridlayout(2, 3)); frame.setdefaultcloseoperation(jframe.exit_on_close); frame.pack(); frame.setvisible(true);  jlabel label = new jlabel(); label.seticon(new imageicon("green.png")); frame.add(label); frame.add(new jbutton("spin")); 

project layout

i've done far, no image appears on jframe. picture in package.

replace

label.seticon(new imageicon("green.png")); 

by

 label.seticon(new imageicon(yourmainclassname.class.getresource("green.png"))); 

this code tries load image relative project, instead of directory, running from. see how use icons section in java tutorial more information.

this code become better, if following fix applied:

jframe frame = new jframe("frame title"); frame.getcontentpane().setlayout(new gridlayout(2, 3)); frame.setdefaultcloseoperation(jframe.exit_on_close); // moved below // frame.pack(); // frame.setvisible(true);  jlabel label = new jlabel(); label.seticon(new imageicon(yourmainclassname.class.getresource("green.png")));  // added items go content pane directly frame.getcontentpane().add(label); frame.getcontentpane().add(new jbutton("spin"));  // moved above frame.pack(); frame.setvisible(true); 

notice jframe contains no content when pack called in original code, try minimize window size, , setvisible show empty frame first. after that, when each component added, frame needs relayout.

modified coded fixes both of problems: pack adjust window size real content , 1 layout pass necessary.

the second change how add components frame. better add them frames content pane, instead of adding frame directly. may find more information in using top-level containers section of java tutorial.


Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -