I have just started gui programming in Java and gave me the background code to JFrame
JLabel By using
I have read many answers to this same question on this website, but for the beginning the code is very complex.
My source code is as follows and the image I am already using is the src
folder (I get the output window but there is no image in it):
increases the public class employee GUI JFrame {Private JLabel imageLabel = new JLab (new image ("employee-directory .jpg")); Private Jepinal BXPanel = new zpn (); Public employee GUI () {super ("employee management"); BxPanel.setLayout (new grid layout (1,1)); BxPanel.add (imageLabel); This.setLayout (new grid layout (1,1)); This.add (bxPanel); This.setVisible (true); This.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); This.setLocationRelativeTo (zero); This.setResizable (wrong); This.pack (); }
"Creates an image icon from the specified file" . The actual physical image is loaded in the background thread, so even if the call can be returned immediately, the actual loading is still going on in the background.
This means that ImageIcon
does not load the image, so do not throw any errors, sometimes work with disturbing. I like to use it wherever possible, because it will throw a IOException
, when it can not read a picture for some reason.
Your image is not loading, this is because the image does not actually exist in context of JVM, which is looking into the current working directory of the image.
When you include resources in the context of the program, they can no longer be addressed as files
For example
< / P>
pre> imageLabel = new jlab (getclass (.) GetResource ("/ staff directory / Employee-directory.jpg "));
Where possible, you should provide the path to the image from the source root reference
Can you give an example that I "ImageIO.read "In my code?
Import java.awt.GridLayout; Import java.awt.image.BufferedImage; Import java.io.IOException; Import javax.imageio.ImageIO; Import javax.swing.ImageIcon; Import javax.swing.JFrame; Import javax.swing.JLabel; Import javax.swing.JPanel; Public class employee GUI JFrame {Personal JLabel imageLabel; Private Jepinal BXPanel = new zpn (); Public employee GUI () {super ("employee management"); ImageLabel = new JLab (); Try {BufferedImage img = ImageIO.read (getClass (). GetResource ("/ staffdirectory / staff-directory.jpg")); ImageLabel.setIcon (New ImageIcon (img)); } Hold (IOException pre) {ex.printStackTrace (); } BxPanel.setLayout (new grid layout (1, 1)); BxPanel.add (imageLabel); This.setLayout (new grid layout (1, 1)); This.add (bxPanel); This.setVisible (true); This.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); This.setLocationRelativeTo (zero); This.setResizable (wrong); This.pack (); }}
No comments:
Post a Comment