import java.awt.*;
import javax.swing.*;
public class Program {
public static JButton button;
public static void main(String args[]){
JFrame win=new JFrame("title");
win.setVisible(true);
win.setSize(500,500);
win.setLayout(new FlowLayout());
win.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon i=new ImageIcon("icon.png");
button=new JButton("hello",i);
win.add(button);
button.setToolTipText("click me");
}
}
When I run the file , I just get the text "hello" on the button but no image.
(This image was downloaded from http://icons.iconarchive.com/icons/iynque/flat-ios7-style-documents/512/png-icon.png)
The image is stored in the project src file.
Image shouldn't be in src but in main application directory, usually level above. So move your icon or change code to:
ImageIcon i=new ImageIcon("src/icon.png");
You should consider adding it to your resources (so it will be placed in jar) and opening via getResource(). Next problem in example is that it won't be displayed until window is refreshed by resize or other action. Add this line at the end:
win.pack();
Or other method that will refresh window content.
try this:
ImageIcon i=new ImageIcon("src/icon.png");
getClass().getResource("icon.png")
will do it, if your image file is under the same dir of the Program.java, and when compiled, it indeed is packed into the same dir where the Program.class is.
Related
I am using JAVA Swing to create a very basic UI. When I run the program, a window will open with a message and browse button(using frame and JButtons for the same). On click of browse button, another window will open to navigate to the file. This I have achieved by calling a FileChooser on the click event of Browse button. However, my program does not wait for user input. The first window with browse button opens and program keeps on executing and ends up in an error as no file has been selected. How do I halt the execution till user input is provided?
In a forum it was advised to use showOpenDialog() method of browser but that straightway opens a browsing window, whereas I want to give the provision to user to click on Browse buttonbrowsewindow
pick file window
My code is below
frame.setLayout(new FlowLayout());
// set up a file picker component
JFilePicker filePicker = new JFilePicker("Pick a file", "Browse...");
filePicker.setMode(JFilePicker.MODE_OPEN);
filePicker.addFileTypeFilter(".jpg", "JPEG Images");
filePicker.addFileTypeFilter(".mp4", "MPEG-4 Videos");
// access JFileChooser class directly
JFileChooser fileChooser = filePicker.getFileChooser();
fileChooser.setCurrentDirectory(new File("C:/"));
// add the component to the frame
frame.add(filePicker);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(520, 100);
frame.setLocationRelativeTo(null); // center on screen
frame.setVisible(true);
System.out.println();
JPicker is the custom class which creates a filechooser and sets things to be done on click of Browse button
Of Course, You set the JFrame visible at the end of its' initialization. You need to do this within the main() method of your startup class. Where is yours?
The JFilePicker (created by: Nam Ha Minh) is applied to a JFrame as a Java Component in order to save a little time in GUI development. I personally would just use the JFileChooser directly within a JButton ActionPerformed event. If you had followed the directions properly then you would see that you need a main() method which only makes sense. What your application Startup class should look like is something like this:
import java.awt.FlowLayout;
import java.io.File;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class TestJFilePicker extends JFrame {
private static final long serialVersionUID = 1L;
public TestJFilePicker() {
super("Test using JFilePicker");
setLayout(new FlowLayout());
// set up a file picker component
JFilePicker filePicker = new JFilePicker("Pick a file", "Browse...");
filePicker.setMode(JFilePicker.MODE_OPEN);
filePicker.addFileTypeFilter(".jpg", "JPEG Images");
filePicker.addFileTypeFilter(".mp4", "MPEG-4 Videos");
// access JFileChooser class directly
JFileChooser fileChooser = filePicker.getFileChooser();
fileChooser.setCurrentDirectory(new File("D:/"));
// add the component to the frame
add(filePicker);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(520, 100);
setLocationRelativeTo(null); // center on screen
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new TestJFilePicker().setVisible(true);
}
});
}
}
The above code (which is the work of Nam Ha Minh) of course assumes that you have already applied the JFilePicker and the FileTypeFilter class files to your project. Without them the above code will not work.
I'm trying yo write a java app with a JFrame object that must show three label objects, with text and image, my text "North" and "South" shows up on execution, but my image does not, even I put the image file into src folder.
package deitel9;
import java.awt.BorderLayout;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JFrame;
public class LabelDemo {
public static void main(String[] args)
{
//crate a label with a plain text
JLabel northLabel = new JLabel("North");
//crate an icon from an image so we can put it on a JLabel
ImageIcon labelIcon = new ImageIcon("maldive.jpg");
//crate a label with an Icon instead of text
JLabel centerLabel = new JLabel(labelIcon);
//create another label with an Icon
JLabel southLabel = new JLabel(labelIcon);
//set the label to display text (as well as an icon)
southLabel.setText("South");
//create a frame to hold the labels
JFrame application = new JFrame();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//add the labels to the frame; the second argument specifies
//where on the frame to add the label
application.add(northLabel,BorderLayout.NORTH);
application.add(centerLabel,BorderLayout.CENTER);
application.add(southLabel,BorderLayout.SOUTH);
application.setSize(300,300);
application.setVisible(true);
}//end main
}//end class LabelDemo
Since your image stored in same package where LabelDemo is stored, try this,
ImageIcon labelIcon = new ImageIcon(LabelDemo.class.getResource("/deitel9/maldive.jpg").getFile());
or
private String getImage() {
return getClass().getResource("/deitel9/maldive.jpg").getFile();
}
ImageIcon labelIcon = new ImageIcon(new LabelDemo().getImage());
To figure out what you did wrong in a situation like this, you can simply call
File file = new File ("maldive.jpg");
System.out.println(file.getAbsolutePath());
This will print out the absolute path it is looking at for your file, which might give you an indication about what you did wrong.
Of course if you know how to use the debugger, you don't need the second line (and technically not even the first one, but that's a bit trickier ;))
According to the documentation, the ImageIcon constructor you chose expects a file name or file path, thus the image needs to be on file system rather than on the class path.
Creates an ImageIcon from the specified file. [...] The specified String can be a file name or a file path.
Given your description, when your project layout looks like this
\---src
\---deitel9
LabelDemo.java
maldive.jpg
then you should be able to retrieve the image as resource located on the class path like this:
ImageIcon labelIcon = new ImageIcon(LabelDemo.class.getResource("maldive.jpg"));
I have added the image in the src and bin directories and cross-checked that the name of the image file is correct
Here is the main class
import javax.swing.*;
public class apples
{
public static void main(String args[])
{
JFrame frame = new JFrame();
MyDrawPanel wid = new MyDrawPanel();
frame.add(wid);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setSize(300,300);
}
}
and here is the class that does the image adding part
import java.awt.*;
import javax.swing.*;
public class MyDrawPanel extends JPanel
{
public void paintComponent(Graphics g)
{
Image image = new ImageIcon("b.png").getImage();
g.drawImage(image,20, 20, this);
}
}
frame.setVisible(true); should be last code line inside public static void main(String args[]), because you setSize to already visible JFrame (just torso contains only Toolbar with three Buttons)
every Swing code lines in public static void main(String args[]) should be wrapped into invokeLater(), more info about in Oracle tutorial Initial Thread
public class MyDrawPanel extends JPanel returns zero Dimension (0, 0) you have to override getPreferredSize for (inside) MyDrawPanel extends JPanel, use there new Dimension (300, 300) from frame.setSize(300,300); and then replace this code line (frame.setSize(300,300);) with frame.pack()
Image image = new ImageIcon("b.png").getImage();
a) don't to load any FileIO inside paintComponent, create this Object as local variable
b) 1st code line inside paintComponent should be super.paintComponent() and without reason to be public, but protected (public void paintComponent(Graphics g))
c) Dimension set in g.drawImage(image,20, 20, this); doesn't corresponding with frame.setSize(300,300);, for why reason is there empty space
d) most important (as mentioned in comments) Image image = new ImageIcon("b.png").getImage(); isn't valid Java path
try to use getClass().getResource("b.png"); instead of simply giving the file name.
Because it sometimes doesn't receive the image, so extract the path and resource.
You have to add your image (or any file) in the main project file when you work with eclipse or other frameworks
and if you decides to specialize a specific folder in the project -to hold images for example- you can write Image image = new ImageIcon("src\\b.png").getImage();//replace the src with folder name
Or add the full (absolute)path
You're declaring a JFrame called frame and correctly declaring a class that inherits from Panel that can be drawn upon. The method paintComponent(Graphics G) in MyDrawPanel.Java is called upon every time the image needs to be rewritten.
I tested out your code in my own IDE and it works for me. I think that, as others also have suggested, that your picture needs to be dragged into your Eclipse IDE. Just drag-and-drop it into your Java-project.
I have this problem in practice, the frame does not display the image I have in the folder image, someone can tell me why? i add the hierarchy of the project
package frame;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Frame {
Frame() {
final JFrame login = new JFrame();
login.setTitle("Title");
login.setLayout(null);
login.add(new JLabel(new ImageIcon("Images/images.png")));
login.setVisible(true);
login.setSize(500, 400);
login.setLocationRelativeTo(null);
}
public static void main(String[] args) {
new Frame();
}
}
Avoid setLayout (null), if you do not have sound reason for it. Remove the below code. Image will get displayed.
If you still have to use a null layout, you have to set the width and height of the component, along with its its x and y position.
login.setLayout(null);
For getting resources from project use URL instead of String path. For example:
URL resource = Frame.class.getResource("/Images/images.png");
ImageIcon icon = new ImageIcon(resource);
JLabel lbl = new JLabel(icon);
Also read that.
Also don't use null LayoutManager, in that case you need to specify bounds of component with help of setBounds() method.
Don't use a package for resources. Instead, create a non-source folder called "images", and move it there.
After that, use that path "images/images.png"
My goal is to have an imageIcon and add it so a JLabel so it will appear on my GUI. So far my code is:
package classes;
import javax.swing.*;
public class Picture extends JFrame {
private ImageIcon _image1;
private JLabel _mainLabel;
public Picture(){
_image1 = new ImageIcon("picture1.jpg");
_mainLabel = new JLabel(_image1);
add(_mainLabel);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
package classes;
public class Driver {
public static void main(String[] args) {
Picture p = new Picture();
}
}
The problem is the picture does not appear on my GUI. If anyone has any suggestions please let me know thanks!
Are you sure that Java is looking in the right location for your picture1.jpg file? Is this file located in the current working directory?
Put this code somewhere in your program so that it gets called when the program is run:
// show the current working directory
System.out.println("current working directory is: " + System.getProperty("user.dir"));
The String returned will tell you where Java is looking, where your current working directory is located. You can then use that information to adjust your path or you could always just use the full path to the image file.
Edit:
Also, don't forget to pack your JFrame so that it will layout the components and size itself accordingly:
public Picture() {
_image1 = new ImageIcon(IMAGE);
_mainLabel = new JLabel(_image1);
add(_mainLabel);
pack(); // to tell the layout managers to set up the GUI
setLocationRelativeTo(null); // center things
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
For setting image to jlabel simple put one line code in your program :
yourlabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("your image location here")));
we can set Jlabel with image and text also.