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: -
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);
-
-
-
-
}
-
-
-
}
-
7 3180 JosAH 11,448
Recognized Expert MVP
At what line does your NullPointerExce ption occur?
kind regards,
Jos
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
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.
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.
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
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: -
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);
-
-
panel_1.draw();
-
}
-
-
-
}
-
-
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);
-
-
-
-
-
//set up window
-
add (panelImages, BorderLayout.CENTER);
-
add (panelButtons, BorderLayout.SOUTH);
-
-
}
-
-
public void draw()
-
{
-
-
Graphics g = panelImages.getGraphics();
-
g.drawImage (imageList[0], 0, 0, panelImages);
-
}
-
-
}
-
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
Sign in to post your reply or Sign up for a free account.
Similar topics |
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...
|
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);
|
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
|
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...
|
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...
| |
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
|
by: Overseer |
last post by:
What is the best way to draw graphics like Task Manager's Performance
Graphic??
|
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);
|
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>
|
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.
|
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...
| |
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,...
|
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...
|
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();...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
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
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
|
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...
| |