I am trying to write a simple program which will allow users to view pictures. I am loading an image as an icon, then assigning that ImageIcon to an Image object. Then i get the graphics context of my panel. Finally I am trying to use the drawImage method to draw the Image object to the panel. However I keep getting a nullpointerexce ption when I run the program. I think it has something to do with the drawImage statement I use but I don't know. Any help would be greatly appreciated.
Here is my source code:
Here is my source code:
Code:
public class ItemPictureViewer
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Image Demo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
DemoPane panel_1 = new DemoPane();
frame.setPreferredSize (new Dimension (250,325));
frame.getContentPane().add(panel_1);
frame.setLocationRelativeTo (null);
frame.pack();
frame.setVisible(true);
}
}
class DemoPane extends JPanel
{
JPanel panelImages, panelButtons;
JButton btnRight, btnLeft;
JLabel labelPics;
final int WIDTH = 250, HEIGHT = 325;
Image eyeball, dewgrass, dna, dock, face;
ImageIcon eyeballIcon, dewgrassIcon, dnaIcon, dockIcon, faceIcon;
Image[] imageList;
public DemoPane()
{
//assign images to the icons
eyeballIcon = new ImageIcon ("EyeBall.jpg");
dewgrassIcon = new ImageIcon ("DewGrass.jpg");
dnaIcon = new ImageIcon ("DNA.jpg");
dockIcon = new ImageIcon ("Dock.jpg");
faceIcon = new ImageIcon ("Face.jpg");
//assign the icons to their respective images
eyeball = eyeballIcon.getImage();
dewgrass = dewgrassIcon.getImage();
dock = dockIcon.getImage();
dna = dnaIcon.getImage();
face = faceIcon.getImage();
//set up image array
Image[] imageList = {eyeball,
dewgrass,
dock,
dna,
face};
//set pane layout
setLayout (new BorderLayout());
//set up panels
panelImages = new JPanel();
panelButtons = new JPanel();
//set up label
labelPics = new JLabel();
//set up buttons
btnRight = new JButton ("Next");
btnLeft = new JButton ("Previous");
//set up layout of buttons
panelButtons.setLayout (new GridLayout (1,2));
panelButtons.add (btnLeft);
panelButtons.add (btnRight);
//draw image to panelImages
Graphics g = panelImages.getGraphics();
g.drawImage (imageList[1], 1, 1, panelImages);
//set up window
add (panelImages, BorderLayout.CENTER);
add (panelButtons, BorderLayout.SOUTH);
}
}
Comment