My question is about Image not appearing when jlabel is clicked from menu
Why does the image does not appear when I click from menu? Please help. Newbie here
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.event.*;
public class Lab05Part02 extends JFrame implements ActionListener{
JMenuItem b1,b2,b3;
JLabel bankImg;
ImageIcon img1 = new ImageIcon("aib.jpg");
ImageIcon img2 = new ImageIcon("BOI.jpg");
ImageIcon img3 = new ImageIcon("kbc.jpeg");
Lab05Part02(){
JMenuBar mb = new JMenuBar();
JMenu banks = new JMenu("Banks", false);
banks.add(b1 = new JMenuItem("AIB"));
b1.addActionListener(this);
banks.add(b2 = new JMenuItem("Bank of Ireland"));
b2.addActionListener(this);
banks.add(b3 = new JMenuItem("KBC"));
b3.addActionListener(this);
mb.add(banks);
setJMenuBar(mb);
JPanel p = new JPanel();
bankImg = new JLabel();
p.add(bankImg);
getContentPane().add(p);
setSize(500,500);
setVisible(true);
}//end of constructor
public static void main(String[] args){
Lab05Part02 myMenu = new Lab05Part02();
}//end of main method
public void actionPerformed(ActionEvent e){
Object source = new Object();
if(source == b1){
bankImg.setIcon(img1);
}
else if(source == b2){
bankImg.setIcon(img2);
}
else if(source == b3){
bankImg.setIcon(img3);
}
else{
bankImg.setText("Select Image from Menu");
}
}//end of listener method
}//end of class
Where did I go wrong? On else if statements? Can someone explain this to me? I did putting setVisible(true) on every condition but it did not work. Thank you in advance!
In the actionPerformed method you forgot to get the source object from the ActionEvent e and you just created a new object:
Object source = new Object();
As it's obvious, in this way source is not equals to the reference of one of your buttons.
The ActionEvent object contains the source of event. In order to resolve the issue get the source object from ActionEvent e argument:
Object source = e.getSource();
If your images ("aib.jpg", "BOI.jpg" and "kbc.jpeg") are in a right path and your ImageIcon img1, img2, img3 objects populated successfully you are good to go with the above fix.
But I can advise that if you want no further inconvenience for showing images and icons in your project, it's better you put them under a package like resources.images and also create a java class there and name it Resources.java for example.
Then you can create images using the resource stream of Resources.java which is in the same package with images and icons:
package resources.images;
import java.net.URL;
import javax.swing.ImageIcon;
public class Resources {
public static ImageIcon getImageIcon(String name) {
URL imagePath = Resources.class.getResource(name);
return new ImageIcon(imagePath);
}
}
Then in your code you can write
ImageIcon img1 = Resources.getImageIcon("aib.jpg");
instead of
ImageIcon img1 = new ImageIcon("aib.jpg");
This way it will work even if you package your application as a jar file.
Hope this helps.
Related
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.
Im looking to change an Icon when I click a Jbutton. I have button1 rigged up to an action command that prints "On" or "Off". I would like to have the button change icons from an image of an circle meaning off, to an image of a power button meaning on. I've tried many things but haven't been able to find a solution so Im wondering if there is an easy way to do this or if there isn't an easy way, and ill have to make a more complex way for each button. Any advice is greatly appreciated because Im at a dead end. Fell free to edit large blocks or add things because Im open to all ideas. The code is included below
import java.awt.*;
import javax.swing.*;
import java.io.*;
import java.awt.event.*;
public class OnandOff{
public static void main(String[] a){
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(new ButtonDemo());
f.setSize(600,500);
f.setVisible(true);
}
}
class ButtonDemo extends JPanel implements ActionListener {
JTextField jtf;
public ButtonDemo() {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
makeGUI();
}
});
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
setLayout(new FlowLayout());
//sets up icons
ImageIcon OnIcon = new ImageIcon(" On.jpg");
Icon OffIcon = new ImageIcon("Off.jpg");
ImageIcon BlankIcon = new ImageIcon("Blank.jpg");
//creates jbuttons with Action command
ImageIcon button1 = new ImageIcon("Off.jpg");
JButton jb = new JButton(button1);
jb.setActionCommand("On");
jb.addActionListener(this);
add(jb);
ImageIcon button2 = new ImageIcon("Off.jpg");
jb = new JButton(button2);
add(jb);
ImageIcon button3 = new ImageIcon("Off.jpg");
jb = new JButton(button3);
add(jb);
ImageIcon button4 = new ImageIcon("Off.jpg");
jb = new JButton(button4);
add(jb);
}
#Override
//prints on and off when detecting action comand from a jbutton
public void actionPerformed(ActionEvent ae) {
String action = ae.getActionCommand();
if (action.equals("On")) {
System.out.println("Yes Button pressed!");
ImageIcon button1 = new ImageIcon("On.jpg");
TicTacToe.a = 1;
}
else if (action.equals("Off")) {
System.out.println("No Button pressed!");
}
}
You're forgetting to call setIcon(...) on any button. As the AbstractButton API will tell you (this is the parent class of JButton), it is easy to change the icon of any button by simply calling its setIcon(Icon icon) method and pass in the new Icon. In the future, first go to the API as you'll learn much there, including methods that do exactly what you need.
Other suggestions: don't give your variables names that don't match what they are. For instance you're calling an ImageIcon variable "button1" as if it were a JButton, and that will confuse other coders and your future self. Instead why not call it `onIcon" or "offIcon", a name that makes the code self-commenting.
A major problem with your code, and one reason why as written, you can't make it work -- your JButton objects are assigned to local variables, variables that are only visible within the method that they were declared. If you want your JButton objects to be able to have there icons changed in different methods of the class, they must be declared at the class level, not at the method or constructor or deeper level.
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).
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'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"