Java Picture Viewer

Displaying an picture image in Java is pretty easy if you already know how to build a basic JFrame and JPanel. You just do that and then add a JLabel to the JPanel, add the JPanel to the JFrame and within the code use the ImageIcon class to define a picture you can reference in part of hte declaration for the JLabel (see JLabels can have pictures so that’s the key). Look at this code in two classes…

package pictureviewer;
public class PictureViewer {
public static void main(String[] args) {
new AJFrame();
}
}

package pictureviewer;

import javax.swing.*;
public class AJFrame extends JFrame{

AJFrame(){
this.setSize(300,300);
this.setTitle(“MYJframe”);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon pic = new ImageIcon(“01.jpg”);//important
JLabel piclabel = new JLabel(pic);
JPanel panel = new JPanel();
panel.add(piclabel);//important
this.add(panel);
this.setVisible(true);
}
}

Now we just place the file 01.jpg in our project folder (not our source folder, but just outside of that). In eclipse it’s easiest to select the picture in your file explorer and copy it (Ctrl-C) and then paste it in your eclipse program in the Package Explorer.

Now run the program and there you go.

If you need to change the picture on the fly define a new ImageIcon and then use….

piclabel.setIcon(whatevericon);

If you want the icon to be variable just define the icon like…

String sa = “01.jpg”;

ImageIcon pic = new ImageIcon(sa);

and then you can change it however often as you wish through whatever scheme.

An example would be…

package pictureviewer;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
public class AJFrame extends JFrame implements ActionListener{
int a = 1;

ImageIcon pic = new ImageIcon(“0″+a+”.jpg”);
JLabel piclabel = new JLabel(pic);
AJFrame(){
this.setSize(300,300);
this.setTitle(“MYJframe”);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JButton b1 = new JButton(“Click Me”);
b1.addActionListener(this);
JPanel panel = new JPanel();
panel.add(b1);
panel.add(piclabel);

this.add(panel);
this.setVisible(true);
}

@Override
public void actionPerformed(ActionEvent e) {
a = a + 1;
ImageIcon pic = new ImageIcon(“0″+a+”.jpg”);
piclabel.setIcon(pic);
}
}