Question

Problem - Refreshing JPanel with BufferedImage Object

Asked by: abhishek88

In my program , i am drawing on bufferedimage object and then i am painting it to jpanel.
It is working fine
But as i want to implement undo/redo functionalities. i want to set or change bufferedimage object by new one (retreived from the vector) to the jpanel. I am getting the object from vector but it is not refreshing the jpanel means new image is not loaded into the jpanel.

Here is the sample code :

//This is the class whose object i am storing in the vector
public class StoreBufferedImage implements Serializable {
	private BufferedImage bufferimage;
	private int current_index;
	public StoreBufferedImage(BufferedImage bufferimage, int current_index) {
		super();
		this.bufferimage = bufferimage;
		this.current_index = current_index;
	}
	public BufferedImage getBufferimage() {
		return bufferimage;
	}
	public void setBufferimage(BufferedImage bufferimage) {
		this.bufferimage = bufferimage;
	}
	public int getCurrent_index() {
		return current_index;
	}
	public void setCurrent_index(int current_index) {
		this.current_index = current_index;
	}
	
}
 
 
public class TestPanel extends JPanel
{
      public Vector<StoreBufferedImage> undoredo=new Vector<StoreBufferedImage>();
     private BufferedImage img;
     public BufferedImage getImg() {
		return img;
	}
 
 
 
	public void setImg(BufferedImage img) {
		this.img = img;
		repaint();
	}
 
      public void refreshImage(Graphics g)
	{
		if(img==null)
		{
			int w=getWidth();
	        int h=getHeight();
	        
	        img=new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
	        setImg(img);    
	        
	        Graphics2D gd=img.createGraphics();
	        gd.setPaint(Color.WHITE);
	        gd.fillRect(0, 0, w, h);
	        gd.dispose();
	        
	        
		}
		
		g.drawImage(getImg(), 0, 0, (int)(getImg().getWidth()),(int)(getImg().getHeight()), this);
	}
 
 
	public void paint(Graphics g) {
		super.paint(g);
		refreshImage(g);
		repaint();
	}
       
    public void undoAction()
	{
		StoreBufferedImage sbi=(StoreBufferedImage)undoredo.firstElement();	
	        // i am getting the object properly.
		setImg(sbi.getBufferimage());
		repaint();
		//on repaint new image is not loaded into jpanel
	}
}
 
 
// This is the mouse listener in which i am drawing rectangle in drawbox method (not shown 
// here in which i am simply drawing the rectangle)
 
public class TestMouseListener extends MouseAdapter{
 
	TestPanel tp;
	int count=0;
	public TestMouseListener(TestPanel tp)
	{
		this.tp=tp;
	}
	
	public void mousePressed(MouseEvent e) {		
		super.mousePressed(e);		
		tp.setStartpt(e.getPoint());		
	}
 
	
	public void mouseReleased(MouseEvent e) {	
		tp.setEndpt(e.getPoint());		
		tp.drawBox(false);	
		StoreBufferedImage sbi=new StoreBufferedImage(tp.getImg(),++count);
		tp.undoredo.add(sbi);				
	} 
	
}
 
// I am having undo button in my jframe class (not shown here) . I am calling undoAction method //  of TestPanel to perform undo operation.

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-10-30 at 12:50:19ID24859229
Tags

Java

,

Swing

,

AWT

Topics

Java AWT & Swing

,

Java Programming Language

Participating Experts
2
Points
125
Comments
29

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. printing JPanels
    I'm trying to print a set of JPanels to the printer, but only one JPanel is displayed on the screen at a time (there is a next and prev button to pan through the Vector of JPanels). Each JPanel will be printed on a different page. I have tried numerous methods though I woul...
  2. drawing gridlines in JPanel
    I am trying to draw gridlines on JPanel where other components are drag and drop into. Did something like this in the JPanel class public void paint(Graphics g) { super.paint(g); int gridHeight = 10; int widthHeight = 10; Dimension size = ...
  3. Painting on a JPanel in a JScrollPane
    I'm painting on a JPanel by subclassing it and using PaintComponent(Graphics g). I'm putting the JPanel in a JScrollPane that is smaller than the panel, and when I repaint the panel, I can see what is being painted on the panel, through the rest of the user interface, althou...
  4. MouseListener for a JPanel painted on another JPanel
    I have a JPanel painted on another JPanel and I can't get the mouseevents to work for the first JPanel. Essentially, what I have is: public class class1 extends JPanel implements MouseListener { Color c; public class1() { c=Color.RED; addMous...
  5. Java-Applet: Paint an image into JPanel
    Hello, can anybody give me a working code to paint an image (same folder as the .class - file) into a JPanel ? Tried it with JLabel and ImageIcon but I'm having exceptions like "no protocol: image.jpg" when running the applet. Thanx BlueJ

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: CEHJPosted on 2009-10-30 at 12:58:32ID: 25706299

>>public void paint(Graphics g) {

should be

public void paintComponent(Graphics g) {

but the real problem lies in refreshImage: you call setImg with an empty image and then proceed to draw it. What happened to your vector of images?

 

by: objectsPosted on 2009-10-30 at 15:58:31ID: 25707307

> but the real problem lies in refreshImage: you call setImg with an empty image and then proceed to draw it.

thats fine actually

 

by: abhishek88Posted on 2009-10-30 at 20:57:02ID: 25708337

Hey there is problem in my vector
My Vector size is fine . but all elements contains the same image (which is the last one added to it).

Plz help me out in this regard.

 

by: objectsPosted on 2009-10-30 at 21:11:18ID: 25708386

thats correct, you need to make a copy of the image before you add it to the list

http://helpdesk.objects.com.au/java/how-to-convert-an-image-to-a-bufferedimage

 

by: CEHJPosted on 2009-10-30 at 23:27:14ID: 25708706

>>but all elements contains the same image (which is the last one added to it).

That may be because you're adding the same image each time:

>>StoreBufferedImage sbi=new StoreBufferedImage(tp.getImg(),++count);

Make sure tp.getImg is returning what you think it should

 

by: abhishek88Posted on 2009-10-31 at 01:53:55ID: 25708912

No

Whenever mouse is released, last image drawn on jpanel is added to the vector
but whenever i insert the new element
and when i checked later on
all the elements of the vector contains same image(last image drawn).

//This is my getImg method of TestPanel
public BufferedImage getImg() {
		return img;
	} 
//This is what i am doing in mousereleased method
public void mouseReleased(MouseEvent e) {
		
		tp.setEndpt(e.getPoint());
		tp.undoredo.add(new  StoreBufferedImage(tp.getImg(),count++));
		tp.drawBox(false);		
		
	} 

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:

Select allOpen in new window

 

by: CEHJPosted on 2009-10-31 at 02:04:16ID: 25708934

Can you please post your full (runnable) code after making the adjustments mentioned?

 

by: abhishek88Posted on 2009-10-31 at 02:14:01ID: 25708958

OK Fine
Here is the relevant code
Plz Check It out.

//Object stored in vector
public class StoreBufferedImage  {
	private BufferedImage bufferimage;
	private int current_index;
	public StoreBufferedImage(BufferedImage bufferimage, int current_index) {
		super();
		this.bufferimage = bufferimage;
		this.current_index = current_index;
	}
	public BufferedImage getBufferimage() {
		return bufferimage;
	}
	public void setBufferimage(BufferedImage bufferimage) {
		this.bufferimage = bufferimage;
	}
	public int getCurrent_index() {
		return current_index;
	}
	public void setCurrent_index(int current_index) {
		this.current_index = current_index;
	}
	
} 
//Mouse Listener
public class TestMouseListener extends MouseAdapter{ 
	TestPanel tp;
	int count=1;
	public TestMouseListener(TestPanel tp)
	{
		this.tp=tp;
	}
	@Override
	public void mousePressed(MouseEvent e) {
		
		super.mousePressed(e);
		
		tp.setStartpt(e.getPoint());
		
	} 
	@Override
	public void mouseReleased(MouseEvent e) {
		// TODO Auto-generated method stub
		tp.setEndpt(e.getPoint());
		BufferedImage timg=tp.getImg();
		tp.undoredo.add(new StoreBufferedImage(timg,count++));
		tp.drawBox(false);	
		
		
	} 
	
} 
public class TestMouseMotionListener extends MouseMotionAdapter {
      TestPanel tp;      
      
      public TestMouseMotionListener(TestPanel tp)
      {
    	  this.tp=tp;
      }
	@Override
	public void mouseDragged(MouseEvent e) {		
		super.mouseDragged(e);				
		tp.setEndpt(e.getPoint());		
		tp.drawBox(true);		
	}
      
} 

public class TestPanel extends JPanel implements Serializable { 
	
	private Point startpt;
	private Point endpt;
	private TestFrame tf;
	private BufferedImage img;
	
	
	
	
	public Vector<StoreBufferedImage> undoredo=new Vector<StoreBufferedImage>();
	
	public TestPanel(TestFrame tf,int w,int h)
	{
		this.tf=tf;    
		this.setSize(w, h);
        img=new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
        setImg(img);     
        Graphics2D gd=img.createGraphics();
        gd.setPaint(Color.WHITE);
        gd.fillRect(0, 0, w, h);
        gd.dispose(); 
	} 
public void paintComponent(Graphics g) {
		super.paintComponent(g);
		g.drawImage(getImg(), 0, 0, (int)(getImg().getWidth()),(int)(getImg().getHeight()), this); 
	} 
 
	public BufferedImage getImg() {
		return img;
	} 
 
	public void setImg(BufferedImage img) {
		this.img = img;
		repaint();
	}
	
//method called on clicking undo button
	public void undoAction()
	{
		System.out.println("size=" + undoredo.size());
		StoreBufferedImage sbi=(StoreBufferedImage)undoredo.firstElement();		
		setImg(sbi.getBufferimage());		
		repaint();
		
	} 
public synchronized void drawBox(boolean type)
	{
		repaint();
		Graphics2D gd=(Graphics2D)getImg().getGraphics();
		gd.setColor(Color.BLACK);
		int w=(int)(getEndpt().getX()-getStartpt().getX());
		if(w<0)
		{
			w*=-1;
		}		
		int h=(int)(getEndpt().getY() - getStartpt().getY());
		if(h<0)
		{
			h*=-1;
		}
		
		
		gd.drawRect((int)getStartpt().getX(), (int)getStartpt().getY(), w, h);
		
		
		if(type)
		{
			
			gd.setColor(getBackground());		
			gd.fillRect((int)getStartpt().getX(), (int)getStartpt().getY(), w, h);
			
		}
		
		gd.dispose();
		repaint();
		
		
	} 
}
	
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:

Select allOpen in new window

 

by: objectsPosted on 2009-10-31 at 02:27:40ID: 25708994

> all the elements of the vector contains same image(last image drawn).

thats right, you need to add a *copy* as I suggested above

see the link I posted for how to create a copy

 

by: CEHJPosted on 2009-10-31 at 02:28:15ID: 25708995

That's not runnable. In fact it's not even compilable, so can't be the code you're running

 

by: abhishek88Posted on 2009-10-31 at 02:40:16ID: 25709023

Hey Objects,

I have tried your solution but i am not getting the desired output

Your link is all about converting an image to a buffered image

but i am already having the bufferedImage object
 
now how to create a copy of it.

 

by: abhishek88Posted on 2009-10-31 at 02:51:50ID: 25709037

Hey CEHJ,

This is just the relevant code.
I know it does not contain all the classes . Therefore it is not compilable and The code is too large to post here.
BUt this is only code relevant to this specific task.

 

by: CEHJPosted on 2009-10-31 at 03:06:15ID: 25709066

OK, so what should it do - it draws successive rectangles after dragging? And then?

 

by: abhishek88Posted on 2009-10-31 at 03:13:08ID: 25709078

in mouse released, i add the image drawn on jpanel to the vector .
and
then on clicking undo button , i call undoAction method

Now why all the elements of the vector are updated with the current image.
In code , on every mouse released event , i am adding the current image to the last in the vector and then drawing the final rectangle.

That Code is already posted in the previous comments.

 

by: CEHJPosted on 2009-10-31 at 03:26:09ID: 25709108

I'm not entirely sure what the undo action is meant to do...

 

by: objectsPosted on 2009-10-31 at 03:31:35ID: 25709120

> Your link is all about converting an image to a buffered image

it will also work to copy a BufferedImage.

 

by: abhishek88Posted on 2009-10-31 at 03:32:45ID: 25709122

undo action is setting the first element of vector to the jpanel

I am retrieving the first element for now . once i get the first element  i correct that code to perform undo operation.


I am getting the first Element as the current image drawn on the jpanel which is not correct but i should get the image containing the first rectangle drawn on the bufferedimage object on jpanel when i start the program and draw the first rectangle.

Hope you got it.

 

by: CEHJPosted on 2009-10-31 at 05:01:16ID: 25709333

Actually i don't see where you add a *new* image

 

by: abhishek88Posted on 2009-10-31 at 05:04:53ID: 25709351

whenever mouse released event is invoked i am getting the current image drawn on the jpanel and then i am adding it to the vector.

 

by: abhishek88Posted on 2009-10-31 at 05:07:51ID: 25709357

Hey objects,

It makes my BufferedImage object appears black instead of copying it.

 

by: CEHJPosted on 2009-10-31 at 05:07:54ID: 25709358

You might find that 'the current image' is the only image if you only have one reference

 

by: CEHJPosted on 2009-10-31 at 05:13:10ID: 25709384

Sorry - no i think they are not the same image

 

by: CEHJPosted on 2009-10-31 at 05:19:24ID: 25709415

Sorry again ;-) I was right first time

 

by: abhishek88Posted on 2009-10-31 at 05:20:41ID: 25709420

ya i have only one reference of buffered image in my panel
but
i am saving the previous reference in the vector first
then i am calling draw Box method which changes and update the buffered image object,

So you want to say that changing in the bufferedimage object also changes the images in the vector
If that is the case then plz give the proper solution or code so that i can proceed further.

I got stuck in this problem.


 

by: CEHJPosted on 2009-10-31 at 05:58:54ID: 25709563

>>ya i have only one reference of buffered image in my panel

You only have one reference *anywhere* (including in the vector) so you can only display one thing or nothing

 

by: abhishek88Posted on 2009-10-31 at 09:10:19ID: 31648390

Hey Objects!!
Thanks for guidance
I have created the copy of BufferedImage not through your method but through some other method

I am giving you the points to give me the idea of creating the copy of bufferedimage object

 

by: CEHJPosted on 2009-10-31 at 09:14:09ID: 25710279

abhishek88, why would you want 'a copy' in the vector? The point is you'd want different images - they wouldn't be a copy of anything. If not, i'm not sure why you'd want to store them in a vector..?

 

by: CEHJPosted on 2009-10-31 at 09:22:15ID: 25710307

Could you also please post, for the benefit of future visitors, how you applied that answer in your code

 

by: abhishek88Posted on 2009-10-31 at 11:41:34ID: 25710955



I want to store the copy of image in the vector because i want to get the previous image from the vector whenever user presses undo button

The problem that was occuring is
whenever i add element to the vector , all the images of the vector are replaced by the current image because of all points to same image (reference problem) so i am not getting the desired output.

Therefore first i create the copy of the image and then store the image in vector.
so next time whenever i add element to the vector , it won't change all the images and
it just add that element to the last.

Copy BufferedImage object (means making clone of it) and storing it in vector have solved my problem.



20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...