473,748 Members | 2,602 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can't draw graphics.

23 New Member
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:

Expand|Select|Wrap|Line Numbers
  1.  public class ItemPictureViewer
  2.    {
  3.  
  4.        public static void main(String[] args)
  5.       {
  6.  
  7.          JFrame frame = new JFrame("Image Demo");
  8.          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  9.          frame.setResizable(false);
  10.  
  11.          DemoPane panel_1 = new DemoPane();
  12.  
  13.          frame.setPreferredSize (new Dimension (250,325));
  14.          frame.getContentPane().add(panel_1);
  15.          frame.setLocationRelativeTo (null);
  16.          frame.pack();
  17.          frame.setVisible(true);
  18.  
  19.  
  20.       }
  21.  
  22.    }
  23.  
  24.     class DemoPane extends JPanel 
  25.    {
  26.       JPanel panelImages, panelButtons;
  27.       JButton btnRight, btnLeft;
  28.       JLabel labelPics;
  29.       final int WIDTH = 250, HEIGHT = 325;
  30.       Image eyeball, dewgrass, dna, dock, face;
  31.       ImageIcon eyeballIcon, dewgrassIcon, dnaIcon, dockIcon, faceIcon;
  32.       Image[] imageList;
  33.  
  34.  
  35.  
  36.        public DemoPane()
  37.       {    
  38.  
  39.           //assign images to the icons
  40.          eyeballIcon = new ImageIcon ("EyeBall.jpg");
  41.          dewgrassIcon = new ImageIcon ("DewGrass.jpg");
  42.          dnaIcon = new ImageIcon ("DNA.jpg");
  43.          dockIcon = new ImageIcon ("Dock.jpg");
  44.          faceIcon = new ImageIcon ("Face.jpg");
  45.  
  46.           //assign the icons to their respective images
  47.          eyeball = eyeballIcon.getImage();
  48.          dewgrass = dewgrassIcon.getImage();
  49.          dock = dockIcon.getImage();
  50.          dna = dnaIcon.getImage();
  51.          face = faceIcon.getImage();
  52.  
  53.           //set up image array
  54.          Image[] imageList = {eyeball,
  55.                                    dewgrass,
  56.                                    dock,
  57.                                    dna,
  58.                                    face};
  59.  
  60.           //set pane layout
  61.          setLayout (new BorderLayout());
  62.  
  63.          //set up panels
  64.          panelImages = new JPanel();
  65.          panelButtons = new JPanel();
  66.  
  67.           //set up label
  68.          labelPics = new JLabel();
  69.  
  70.           //set up buttons
  71.          btnRight = new JButton ("Next");
  72.          btnLeft = new JButton ("Previous");    
  73.  
  74.           //set up layout of buttons
  75.          panelButtons.setLayout (new GridLayout (1,2));
  76.          panelButtons.add (btnLeft);
  77.          panelButtons.add (btnRight);
  78.  
  79.          //draw image to panelImages
  80.          Graphics g = panelImages.getGraphics();
  81.          g.drawImage (imageList[1], 1, 1, panelImages);     
  82.  
  83.  
  84.           //set up window
  85.          add (panelImages, BorderLayout.CENTER);
  86.          add (panelButtons, BorderLayout.SOUTH);
  87.  
  88.  
  89.  
  90.       }
  91.  
  92.  
  93.    }
  94.  
Sep 11 '08 #1
7 3180
JosAH
11,448 Recognized Expert MVP
At what line does your NullPointerExce ption occur?

kind regards,

Jos
Sep 11 '08 #2
HxRLxY
23 New Member
At what line does your NullPointerExce ption occur?

kind regards,

Jos
This is the message my runtime I/O gives me.

Exception in thread "main" java.lang.NullP ointerException
at DemoPane.<init> (ItemPictureVie wer.java:90)
at ItemPictureView er.main(ItemPic tureViewer.java :20)


Through my feeble attempts at debugging, I found that if I comment-out the line
g.drawImage (imageList[1], 1, 1, panelImages) then the exception doesn't occur. But that actually defeats the purpose of the program. So I'm kinda stuck

Thanks,
HxRLxy
Sep 12 '08 #3
r035198x
13,262 MVP
This is the message my runtime I/O gives me.

Exception in thread "main" java.lang.NullP ointerException
at DemoPane.<init> (ItemPictureVie wer.java:90)
at ItemPictureView er.main(ItemPic tureViewer.java :20)


Through my feeble attempts at debugging, I found that if I comment-out the line
g.drawImage (imageList[1], 1, 1, panelImages) then the exception doesn't occur. But that actually defeats the purpose of the program. So I'm kinda stuck

Thanks,
HxRLxy
So that tells you that one of the objects accessed at that line is null at the time at which that line is invoked. There is only a finite number of objects there so you should be able to devise a way of finding out which one.
Sep 12 '08 #4
HxRLxY
23 New Member
So that tells you that one of the objects accessed at that line is null at the time at which that line is invoked. There is only a finite number of objects there so you should be able to devise a way of finding out which one.
Well I messed around with it some more and found that when I call the Graphics g = panelImages.get Graphics() , the g object that is returned is null. But I can't figure out why it's null. I know that the JPanels have a graphics context. And the Java API says the way to get that object is through the getGraphics method. So I'm really not sure what I'm doing wrong.
Sep 12 '08 #5
JosAH
11,448 Recognized Expert MVP
The documentation tells you that the method will return null if the component is
currently not displayable.

kind regards,

Jos
Sep 12 '08 #6
HxRLxY
23 New Member
Okay. I changed my code to allow the panel to be displayed before calling the getGraphics method. I added a method to the end of my DemoPane class to draw the image after the panel is shown. So now the panelImages.get Graphics call doesn't return null (according to my debugger), however I am still getting a NullPointerExec ption at g.drawImage (imageList[0], 0, 0, null). Thank you again for your help.

Here is my revised code:

Expand|Select|Wrap|Line Numbers
  1.     public class ItemPictureViewer
  2.    {
  3.  
  4.        public static void main(String[] args)
  5.       {
  6.  
  7.          JFrame frame = new JFrame("Image Demo");
  8.          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  9.          frame.setResizable(false);  
  10.  
  11.          DemoPane panel_1 = new DemoPane();
  12.  
  13.          frame.setPreferredSize (new Dimension (250,325));
  14.          frame.getContentPane().add(panel_1);
  15.          frame.setLocationRelativeTo (null);
  16.          frame.pack();
  17.          frame.setVisible(true);
  18.  
  19.          panel_1.draw();
  20.       }
  21.  
  22.  
  23.    }
  24.  
  25.     class DemoPane extends JPanel 
  26.    {
  27.       JPanel panelImages, panelButtons;
  28.       JButton btnRight, btnLeft;
  29.       JLabel labelPics;
  30.       final int WIDTH = 250, HEIGHT = 325;
  31.       Image eyeball, dewgrass, dna, dock, face;
  32.       ImageIcon eyeballIcon, dewgrassIcon, dnaIcon, dockIcon, faceIcon;
  33.       Image[] imageList;
  34.  
  35.  
  36.  
  37.        public DemoPane()
  38.       {    
  39.  
  40.           //assign images to the icons
  41.          eyeballIcon = new ImageIcon ("EyeBall.jpg");
  42.          dewgrassIcon = new ImageIcon ("DewGrass.jpg");
  43.          dnaIcon = new ImageIcon ("DNA.jpg");
  44.          dockIcon = new ImageIcon ("Dock.jpg");
  45.          faceIcon = new ImageIcon ("Face.jpg");
  46.  
  47.           //assign the icons to their respective images
  48.          eyeball = eyeballIcon.getImage();
  49.          dewgrass = dewgrassIcon.getImage();
  50.          dock = dockIcon.getImage();
  51.          dna = dnaIcon.getImage();
  52.          face = faceIcon.getImage();
  53.  
  54.           //set up image array
  55.          Image[] imageList = {eyeball,
  56.                                    dewgrass,
  57.                                    dock,
  58.                                    dna,
  59.                                    face};
  60.  
  61.           //set pane layout
  62.          setLayout (new BorderLayout());
  63.  
  64.          //set up panels
  65.          panelImages = new JPanel();
  66.          panelButtons = new JPanel();
  67.  
  68.           //set up label
  69.          labelPics = new JLabel();
  70.  
  71.           //set up buttons
  72.          btnRight = new JButton ("Next");
  73.          btnLeft = new JButton ("Previous");    
  74.  
  75.           //set up layout of buttons
  76.          panelButtons.setLayout (new GridLayout (1,2));
  77.          panelButtons.add (btnLeft);
  78.          panelButtons.add (btnRight);
  79.  
  80.  
  81.  
  82.  
  83.           //set up window
  84.          add (panelImages, BorderLayout.CENTER);
  85.          add (panelButtons, BorderLayout.SOUTH);
  86.  
  87.       }
  88.  
  89.        public void draw()
  90.       {
  91.  
  92.          Graphics g = panelImages.getGraphics();
  93.          g.drawImage (imageList[0], 0, 0, panelImages);
  94.       }
  95.  
  96.    }
  97.  
Sep 12 '08 #7
JosAH
11,448 Recognized Expert MVP
Have you read (and understood) how painting works in Swing? It is very much
unlike how you attempt to accomplish it. You should implement/override a
paintComponent( ) method that gets a Graphics object passed as its parameter
and is called by the AWT dispatch thread whenever needed.

kind regards,

Jos
Sep 13 '08 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

0
1294
by: Jan Kopcsek | last post by:
Hello, is there a way to draw Windows.Forms components into a specified surface (a D3DSurface for example)? i want to fill a texture with the graphics and render it to the screen. it looks like it's hard to pass the Graphics object throught the component hierarchy because no public method takes an PaintEventArgs object or Graphics object. Invalidate, Repaint and so on all seem to get their Graphics object from nowhere (ok, after reading...
6
1771
by: John | last post by:
I wrote this class class CLine { public float sX,sY,dX,dY,m,x,y; public void Draw (PaintEventArgs g) { //Graphics g = this.CreateGraphics (); Bitmap bm=new Bitmap(1,1);
3
10325
by: Colin McGuire | last post by:
Hi there. I have written a small procedure to draw various shapes on things. A bit of it is shown below. Private Sub drawShape(ByVal shapeType As Integer, ByRef g As Graphics) Select Case shapeType Case 1 : g.DrawRectangle(New Pen(Color.Black), 0, 0, 50, 10) Case 2 'draw a circle Case 3 'draw a triangle Case 4 'draw other shape Case 5 'draw other shape
1
3568
by: Robin Tucker | last post by:
Hi ppl, My owner draw list box controls do not "refresh" old selected items when a new selection is made. This means that as you click to make selections, the previously selected items stay highlighted along with the new ones too. It draws correctly when I minimize the window and then maximise it again, but I just don't seem to be getting a "DrawItem" event for switching of an item from Selected to NotSelected! Any ideas??? Here is...
2
3136
by: dan heskett | last post by:
I am owner-drawing a listbox, in an attempt to create a nice list with some custom "fields" and text layout. Essentially it works, but I must be missing something big, conceptually, because I get all kinds of screen artifacts and weirdness. My general goal is: list item with a few areas for text, every other item shaded a light color for readability, font color changes with selection. The listbox is populated with custom structurs...
0
2286
by: Smokey Grindle | last post by:
This is just a wierd one... I am trying to draw the sub items in the drawitem event of the list view in owner drawn mode (because of documented W32 rendering bugs) instead of in two seperate items drawitem and drawsubitems... but when I run this code in the drawitems For Each subItm As ListViewItem.ListViewSubItem In _tn.SubItems ' If subItm..ColumnIndex <0 Then 'If (e.State And Windows.Forms.ListViewItemStates.Selected) = 1 Then
2
4224
by: Overseer | last post by:
What is the best way to draw graphics like Task Manager's Performance Graphic??
2
1615
by: =?Utf-8?B?S3VuIE5pdQ==?= | last post by:
Dear all, I'm new here and I'm sorry to trouble. But I've got the following problem when trying to draw a PNG file on a panel. My code is like this: Image mapImage = Image.FromFile (imageFileNames); Graphics graphics = this.splitContainer1.Panel1.CreateGraphics(); graphics.Clear(this.splitContainer1.Panel1.BackColor); graphics.DrawImage(mapImage, 10, 10, 50, 50);
14
1884
by: Joe | last post by:
this file is drawn in VB.NET and input output goes by XmlSerializer. Therefore, simple output file looks like: <?xml version="1.0" encoding="utf-8"?> <DrawablePicture xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" BackColor="-1250856"> <DrawableRectangle LineWidth="2" X1="377" Y1="88" X2="323" Y2="130" ForeColor="-16777216" BackColor="-1" /> </DrawablePicture>
8
3548
by: ofiras | last post by:
Hi, I made a "Paint" program, but I couldn't find a method to paint 1 pixel using graphic state ("Graphics g = Graphics.FromHwnd(this.Handle);") How can I paint 1 pixel? I guess I can make a Bitmap, change one pixel color and show it, but I'm sure there is another way of doing it. Please help, Ofir.
0
8984
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8823
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8237
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6073
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4593
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4864
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3300
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2775
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2206
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.