The problem is that the image is not getting loaded while I run the following swing program.
I have a package called "sWINGPRAC" inside which I have a JAVA file IconLabelDemo.java. I have ensured that the Image "myIcon.gif" is in the same directory.
IconLabelDemo.java.
package sWINGPRAC;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
public class IconLabelDemo {
public IconLabelDemo() {
JFrame jfrm = new JFrame("ImageIcon");
jfrm.getContentPane().setLayout(new GridLayout(4, 1));
jfrm.setSize(250, 300);
jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon img = new ImageIcon("myIcon.gif");
JLabel jlabIcon = new JLabel(img);
JLabel jlabIconTxt = new JLabel("Default iCon and text position",img , SwingConstants.CENTER);
JLabel jlabIconTxt2 = new JLabel("Text left of icon",img,SwingConstants.CENTER);
jlabIconTxt2.setHorizontalTextPosition(SwingConstants.LEFT);
JLabel jlabIconTxt3 = new JLabel("Text Over ICon",img,SwingConstants.CENTER);
jlabIconTxt3.setVerticalTextPosition(SwingConstants.TOP);
jfrm.add(jlabIcon);
jfrm.add(jlabIconTxt);
jfrm.add(jlabIconTxt2);
jfrm.add(jlabIconTxt3);
jfrm.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
new IconLabelDemo();
}
});
}
}
Nadir has hit the nail on the head with his comment. You are using "myIcon.gif" as a filename, which means it has to be local to the directory where the program is executed. If you want to package the icon with your library, you need to look into using resource loaders. Have a look at this question: How to correctly get image from 'Resources' folder in NetBeans (it should apply in Eclipse also).
Related
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.
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();
}
}
I'm trying to add an image to a JFrame and set its location, I don't know why it just does not add into it, maybe I don't understand how the JFrame class works since a normal text JLabel adds into the JFrame simply without any trouble and a JLabel containing an image simply does not add in.
I would appreciate if someone would explain the error in the code, and maybe even give me a short explanation of why my way does not work. Thanks!
import java.awt.*;
import javax.swing.*;
public class Walk {
public static void main(String[] args) {
JFrame f = new JFrame("Study");
f.setSize(3000,1000);
f.getContentPane().setBackground(Color.white);
f.getContentPane().add(new JLabel("test", JLabel.CENTER) );
JLabel l = new JLabel(new ImageIcon("C:\\Users\\leguy\\OneDrive\\Desktop\\Stuff\\stillsp"));
l.setBounds(100, 100, 100, 100);
l.setVisible(true);
f.add(l);
f.setVisible(true);
}
}
are you using a gui class or you are writing its code into a main class
what is in your code is that you are writing its code so easy way is to just drag and drop try this link for normal jframes gui eclipse gui
about the picture into jframe is easy one all what you have to do is
1. create a label by setting its size as you want on the jframe by dragging and dropping only
2. follow the pictures
then you browser for your picture you want
select the picture and its done
Hope it helps
Make sure the path to your image is valid. All I did was point to a valid image on my PC and the code practically worked. There were a few things added and organized below.
import java.awt.Color;
import javax.swing.*;
public class Walk {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() { // Safety first...
#Override
public void run() {
String path = "C:\\Path\\To\\Image.png"; // Make sure it's correct
JFrame frame = new JFrame("Study");
JLabel label = new JLabel(new ImageIcon(path));
frame.setSize(3000, 1000);
frame.getContentPane().setBackground(Color.white);
frame.getContentPane().add(new JLabel("test", JLabel.CENTER));
label.setBounds(100, 100, 100, 100);
label.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(label);
frame.pack(); // Pack the frame's components.
frame.setVisible(true);
}
});
}
}
To make sure both labels show up, provide a layout and add them accordingly.
import java.awt.*;
import javax.swing.*;
public class Walk {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
String path = "C:\\Path\\To\\Image.png"; // Make sure it's correct
JFrame frame = new JFrame("Study");
Container container = frame.getContentPane();
JLabel imageLbl = new JLabel(new ImageIcon(path));
JLabel textLbl = new JLabel("test");
frame.setLayout(new BorderLayout());
frame.setSize(3000, 1000);
imageLbl.setBounds(100, 100, 100, 100);
imageLbl.setVisible(true);
container.setBackground(Color.WHITE);
container.add(textLbl, BorderLayout.NORTH);
container.add(imageLbl, BorderLayout.CENTER);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
});
}
}
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);
I have to create a Swing applet for a school assignment, and was given a link (http://java.sun.com/docs/books/tutorial/uiswing/components/index.html) to look at various Swing tutorials and use one of them to create a unique Java applet. I chose to follow the code for the How To Use Radio Buttons tutorial. I read through the code and typed it up while changing things so that they would match my pictures. The code I have is
package components;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class OSButtons extends JPanel implements ActionListener {
static String windowsString = "Windows";
static String linuxString = "Linux";
static String macString = "Mac";
JLabel picture;
public OSButtons() {
super(new BorderLayout());
JRadioButton windowsButton = new JRadioButton(windowsString);
windowsButton.setMnemonic(KeyEvent.VK_W);
windowsButton.setActionCommand(windowsString);
windowsButton.setSelected(true);
JRadioButton linuxButton = new JRadioButton(linuxString);
linuxButton.setMnemonic(KeyEvent.VK_L);
linuxButton.setActionCommand(linuxString);
JRadioButton macButton = new JRadioButton(macString);
macButton.setMnemonic(KeyEvent.VK_M);
macButton.setActionCommand(macString);
ButtonGroup group = new ButtonGroup();
group.add(windowsButton);
group.add(linuxButton);
group.add(macButton);
windowsButton.addActionListener(this);
linuxButton.addActionListener(this);
macButton.addActionListener(this);
picture = new JLabel(createImageIcon("images/" + windowsString + ".gif"));
picture.setPreferredSize(new Dimension(200, 150));
JPanel radioPanel = new JPanel(new GridLayout(0, 1));
radioPanel.add(windowsButton);
radioPanel.add(linuxButton);
radioPanel.add(macButton);
add(radioPanel, BorderLayout.LINE_START);
add(picture, BorderLayout.CENTER);
setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));
}
public void actionPerformed(ActionEvent e) {
picture.setIcon(createImageIcon("images/" + e.getActionCommand() + ".gif"));
}
protected static ImageIcon createImageIcon(String path) {
java.net.URL imgURL = OSButtons.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("OSButtons");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new RadioButtonDemo();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
I hope that's readable. Anyways, I compiled the code and it came up with these errors:
I really have no idea how to proceed from here as far as fixing these, this assignment was kind of thrown onto me and I had to research Swing, SWT, and AWT completely on my own. Any help that could be offered would be greatly appreciated.
Change...
picture = newJLabel(createImageIcon("images/"+ windowsString + ".gif"));
to...
picture = new JLabel(createImageIcon("images/"+ windowsString + ".gif"));
Change
radiopanel.add(macButton);
to...
radioPanel.add(macButton);
Java is case sensitve, variable names case must match
This...
JComponent newContentPane = new RadioButtonDemo();
I suspect is a copy/paste error. You change the class name of the original code, but forgot to change any references to it.
Try...
JComponent newContentPane = new OSButtons();
Instead
Update
Okay. Let's assume that you have your source files in C:\Users\Keith\Desktop\components.
At the command prompt your would compile them by using something like...
C:\> cd C:\Users\Keith\Desktop
C:\Users\Keith\Desktop> javac components.OSButtons.java
C:\Users\Keith\Desktop> java components.OSButtons
There is a direct coalition between the package name and the expected directory of the class files.