How to add an ImageIcon to a JFrame? - java

I'm trying to add an image to one frame but it seems it does not working. The image created by an ImageIcon from the specified file. The image file is in the seam directory the java file exist.
import java.awt.BorderLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class image {
public static void main(String args[])
{
TimeFrame frame = new TimeFrame();
}
}
class TimeFrame extends JFrame
{
//Image icon = Toolkit.getDefaultToolkit().getImage("me.jpg");
ImageIcon icon = new ImageIcon("me.jpg");
JLabel label = new JLabel(icon);
public TimeFrame(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("My Frame");
setSize(500,400);
//this.setIconImage(icon);
add(label,BorderLayout.CENTER);
setVisible(true);
}
}

If your icon is beside the TimeFrame java file, you should use
java.net.URL imgUrl = getClass().getResource("me.jpg");
ImageIcon icon = new ImageIcon(imgUrl);
or
java.net.URL imgUrl = TimeFrame.class.getResource("me.jpg");
ImageIcon icon = new ImageIcon(imgUrl);
You are (probably) currently looking for it in your working directory which you can output via
System.out.println(System.getProperty("user.dir"));

Will u try this one?
ImageIcon ImageIcon = new ImageIcon("me.jpg");
Image Image = ImageIcon.getImage();
this.setIconImage(Image);

Simply change the directory to "src/me.jpg"

Related

Intellij Java - ImageIcon window runs but no image displayed

I am having an issue with getting my image to display within the GUI window. The GUI initiates fine but no image is displayed window displays no image. I have tired various methods with no luck and I'm not sure where I'm going wrong. Any guidance would be greatly appreciated
package banksystem;
import javax.swing.*;
import java.awt.*;
public class Login extends JFrame {
Login(){
setTitle("Cash Machine");
ImageIcon img1 = new ImageIcon(ClassLoader.getSystemResource("bank-icon.jpg"));
Image img2 = img1.getImage().getScaledInstance(100,100, Image.SCALE_DEFAULT);
ImageIcon img3 = new ImageIcon(img2);
JLabel label = new JLabel(img3);
add(label);
setSize(800, 480); //Sets frame size
setVisible(true); //Frame will display
setLocation(350, 200); //Sets frame location
}
public static void main(String[] args) {
new Login();
}
}
folder setup within intellij
ImageIcon img1 = new ImageIcon(ClassLoader.getSystemResource("/images/bank-icon.jpg"));
Also, move resources directory outside of the sources root.

setIcon of JLabel is not working, but setIconImage of JFrame is

I am using VS Code and my folder contains one Java file and one image only.
I was trying to set image in JLabel, so first I access the image by:
ImageIcon img = new ImageIcon(getClass().getResource("img_flag.png"));
Then I set this to JLabel but nothing appears on my screen.
JLabel label = new JLabel(img);
To confirm that I am accessing the correct image, I set it to the logo of the window and the logo was showing properly.
setIconImage(img.getImage());
I can't figure out why label can't show the image.
Here is my full code:
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Mylable extends JFrame{
Mylable(){
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(500,500);
ImageIcon img = new ImageIcon(getClass().getResource("img_flag.png"));
setIconImage(img.getImage()); //working
JLabel label = new JLabel(img); //not working
add(label);
}
public static void main(String[] args) {
new Mylable();
}
}

How can I not show the open dialog first?

Well, the only problem I am having is that the open dialog is showing first. What I want is to only to put it inside the JFrame and then do the rest inside the JFrame like opening image and display it. It should be like this
The problem is that my JFileChooser is showing first. And also the thing is I want it all to be inside the JFrame just like in the image shown.
Here is my code:
import java.awt.Image;
import java.io.File;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.border.*;
import java.awt.Color;
import java.awt.Dimension;
public class imgviewer extends JFrame{
JButton button;
JLabel label;
public imgviewer() {
super("Image viewer");
label = new JLabel();
label.setBounds(400, 10, 180, 300);
Border b = BorderFactory.createLineBorder(Color.ORANGE, 2);
JFileChooser file = new JFileChooser(".");
label.setBorder(b);
add(label);
file.setPreferredSize(new Dimension(400, 300));
file.setCurrentDirectory(new File(System.getProperty("user.home")));
FileNameExtensionFilter filter = new FileNameExtensionFilter("*.Images", "jpg", "png", "gif");
file.addChoosableFileFilter(filter);
int result = file.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = file.getSelectedFile();
String path = selectedFile.getAbsolutePath();
label.setIcon(ResizeImage(path));
}
else if (result == JFileChooser.CANCEL_OPTION) {
System.out.println("No File Selected");
}
add(file);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setSize(600, 350);
setVisible(true);
}
public ImageIcon ResizeImage(String ImagePath) {
ImageIcon MyImage = new ImageIcon(ImagePath);
Image img = MyImage.getImage();
Image newImg = img.getScaledInstance(label.getWidth(), label.getHeight(), Image.SCALE_SMOOTH);
ImageIcon image = new ImageIcon(newImg);
return image;
}
public static void main(String[] args) {
new imgviewer();
}
}
I'm not sure how to do what you want to do, but where you put the line int result = file.showOpenDialog(null); into your code, that's a line that explicitly means "open this JFileChooser in its own file dialog NOW". In the order of your code, that clearly happens before the setVisible(true) line which would open the wrapper you wish to put around the file dialog.
Is there a reason the code after file.addChoosableFileFilter(filter);, and before add(file), is indented? If you were imagining that this code is in a separate block which will prevent it from being executed until later, it isn't.
I haven't worked with JFileChooser, or Swing in general, for a long time now, so I don't know off hand how well a JFileChooser will work if treated as a separate component embedded inside another component, but if that's going to work at all, you definitely cannot use JFileChooser's showOpenDialog method.

Java - How do I get an image to display?

I have spent a really long time trying to find a way to display an image in a Java program (I'm trying to learn how to make a 2D Java game) an nothing that I've tried works. I'm using Eclipse Mars and the latest of everything else. Here is my code:
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main extends JFrame {
public static void main(String[] args0) {
JFrame frame = new JFrame();
ImageIcon image = new ImageIcon("background.bmp");
JLabel imageLabel = new JLabel(image);
frame.add(imageLabel);
frame.setLayout(null);
imageLabel.setLocation(0, 0);
imageLabel.setSize(1000, 750);
imageLabel.setVisible(true);
frame.setVisible(true);
frame.setSize(1000, 750);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Please, just tell me how to correct the code so that the image actually displays. Thank you ahead of time.
(P.S. the "background.bmp" file is in the "default package" if that changes anything)
The image with .bmp suffix can't be displayed in your code. Try to modify
ImageIcon image = new ImageIcon("background.bmp");
to
ImageIcon image = new ImageIcon("background.png");
and change the image name to background.png.
However, if you just want to use background.bmp, you need to modify your code like this and background image will be displayed.
import java.awt.Image;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Main extends JFrame {
public static void main(String[] args0) {
try {
JFrame frame = new JFrame();
File imageFile = new File("background.bmp");
Image i = ImageIO.read(imageFile);
ImageIcon image = new ImageIcon(i);
JLabel imageLabel = new JLabel(image);
frame.add(imageLabel);
frame.setLayout(null);
imageLabel.setLocation(0, 0);
imageLabel.setSize(1000, 750);
imageLabel.setVisible(true);
frame.setVisible(true);
frame.setSize(1000, 750);
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Here is the effect with new code:
Hope it helps.
BTW, I've put the image at the root directory of the project.
Read the section from the Swing tutorial on How to Use Icons. The examples their show you how to load the images as resources. When you use resources the classpath will be searched to find the file.
//frame.setLayout(null);
//imageLabel.setLocation(0, 0);
//imageLabel.setSize(1000, 750);
Don't use a null layout and attempt to set the size/location of the label. Let the layout manager do its job. The label will be the size of the image.
//frame.setSize(1000, 750);
frame.pack();
Don't use frame.setSize(...). Instead you use frame.pack() then the frame will be the size of the image plus the size of the frame borders and title. Let Swing and its layout managers do the work for you.
As a beginer, I found that is easy to see the picture you draw:
Source code
public class CheckCodeTest {
private int width = 100, height = 50;
private BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
#Test
public void drawGraphicsTest() throws IOException {
Graphics graphics = image.createGraphics();
// draw an orange rectangle
graphics.setColor(Color.orange);
graphics.fillRect(0,0,width,height);
// layout the picture right now!
graphics.drawImage(image,0,0,null);
ImageIO.write(image, "png", new File("checkcode.png"));
}
}
Output
It produce a picture file under your projects content.
output-picture
Then you can see what change after adding draw code in small window, it is more convenient than closing an jump-out Frame / Label window:
output-picture-in-editor

Java - Getting Thumbnail of File and Resizing

I'm trying to get the Thumbnail that is associated to a particular file, and then resize it. I've been testing on Mac, and haven't been able to find a solution that would allow me to achieve this.
Code so far:
import com.apple.laf.AquaIcon;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
public class TestSystemIcon extends JFrame
{
JPanel panel;
ImageIcon icon;
public TestSystemIcon()
{
panel = new JPanel();
JButton button = new JButton("Open...");
final JLabel label = new JLabel();
icon = null;
final JPanel en = new JPanel(new FlowLayout(FlowLayout.CENTER));
label.setHorizontalAlignment(SwingConstants.CENTER);
button.addActionListener(new ActionListener()
{
#Override
public void actionPerformed(ActionEvent e)
{
JFileChooser fileChooser = new JFileChooser();
if(fileChooser.showOpenDialog(null) == JFileChooser.OPEN_DIALOG)
{
File file = fileChooser.getSelectedFile();
icon = resizeIcon(getThumbnail1(file),200,200);
// icon = resizeIcon(getThumbnail2(file),200,200);
System.out.println(icon);
label.setIcon(icon);
en.add(label);
revalidate();
repaint();
}
}
});
panel.add(button);
this.add(panel,BorderLayout.NORTH);
this.add(en,BorderLayout.CENTER);
this.setSize(400,400);
this.setLocationRelativeTo(null);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public ImageIcon getThumbnail1(File file)
{
JFileChooser f = new JFileChooser();
Icon i = f.getIcon(file);
//Mac Conversion.
Image image = AquaIcon.getImageForIcon(i);
return new ImageIcon(image);
}
public ImageIcon getThumbnail2(File file)
{
return new ImageIcon(file.getPath());
}
public ImageIcon resizeIcon(ImageIcon imageIcon,int width, int height)
{
return new ImageIcon(imageIcon.getImage().getScaledInstance(width,height,Image.SCALE_SMOOTH));
}
public static void main(String[] args)
{
TestSystemIcon test = new TestSystemIcon();
test.setVisible(true);
}
}
Version1 of getting the thumbnail has following behaviour:
Can open thumbnails
Very small, scaling not suitable.
Version2 of getting thumbnail has following behaviour:
Doesn't display image, despite finding image (System.out proves this).
Except for pdf, where instead it displays the actual file, as opposed to the
thumbnail
When it does work i.e. pdf, it scales nicely.
I know I can use sun.awt.shell.ShellFolder;, however I am aiming for a cross-platform solution.
Thanks for any help
I looked at some code that I have done in the past and seems this works fine when you use JLabel with and ImageIcon, try this code that resized a large image to 100x100,
ImageIcon icon = new ImageIcon("Penguins.jpg");
Image img = icon.getImage().getScaledInstance(100,100,Image.SCALE_SMOOTH);
// if the file is not an image, but a file on the system,
Icon icon = FileSystemView.getFileSystemView().getSystemIcon(file);
Image img = ((ImageIcon) icon).getImage().getScaledInstance(100,100,Image.SCALE_SMOOTH);
ImageIcon icon1 = new ImageIcon(img);
JLabel image = new JLabel(icon1);

Categories

Resources