Results 1 to 17 of 17
  1. #1
    Melodia is offline Member
    Join Date
    Sep 2013
    Posts
    18
    Rep Power
    0

    Default Stopping my lines from disappearing.

    Hi, I was wondering if anyone could tell me how to stop lines drawn on a JPanel to stop disappearing. I have made a project in which I can draw one line at a time with two clicks of the mouse, but it is done in such a way that each line will disappear as soon as the next one starts. The three classes I have made are shown below:

    Java Code:
    package lineProject;
    
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.io.IOException;
    
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    public class DrawingFrame extends JPanel {
    	
    
    	public static void main(String[] args) throws IOException {
    
    		JFrame frame = new JFrame("Draw a line");
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    		frame.setSize(400, 400);
    
    
    		frame.setPreferredSize(new Dimension(400,400));
    		DrawingPanel dp = new DrawingPanel();
    		frame.add(dp,BorderLayout.CENTER);
    
    		
    		frame.pack();
    		frame.setVisible(true);
    
    	}
    
    }
    Java Code:
    package lineProject;
    
    import java.awt.Color;
    import java.awt.Dimension;
    
    import javax.swing.JPanel;
    
    public class DrawingPanel extends JPanel {
    
    	public DrawingPanel(){
    		setSize(400,400);
    		setPreferredSize(new Dimension(1000,1000));
    		setBackground(Color.white);
    		Line line = new Line();
    		add(line);
    		setVisible(true);
    
    	}
    }
    Java Code:
    package lineProject;
    
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Point;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    
    import javax.swing.JComponent;
    
    
    public class Line extends JComponent {
    	Point p1,p2;
    	
    	public Line(){
    	
    	addMouseListener(new MouseAdapter() {
         @Override
         public void mouseClicked(MouseEvent e) {
            if (p1 == null || p2 != null) { 
                  p1 = e.getPoint();
                  p2 = null;
              } else {
                 p2 = e.getPoint();
            } 
    repaint();     }
      });
    	setPreferredSize(new Dimension(400,300));}
    	
    	protected void paintComponent(Graphics g) {
          super.paintComponent(g);
         if(p1 != null && p2 != null) {
             g.drawLine(p1.x, p1.y,p2.x,p2.y);
    	
    	
    	
    	}
    		
    	
    	}}
    From noticing responses to people with similar problems, it seems that double buffering is something I could use, but I am totally unfamiliar with it, and any tutorials I find on it seem to be lacking in actual examples. So, if someone can give me an example, or at least direct me to a tutorial which is better than the ones I have seen so far, I would be very grateful.

    Thank you all!

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,875
    Rep Power
    25

    Default Re: Stopping my lines from disappearing.

    If you want save what was drawn previously, draw the line on an image and draw that image in the paintComponent() method. Something like this:
    create image
    begin loop
    draw line on image
    draw the image
    end loop

    The loop I refer to is an implicit loop between calls to repaint() and calls to printComponent(), not an explicit loop in your code.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    Melodia is offline Member
    Join Date
    Sep 2013
    Posts
    18
    Rep Power
    0

    Default Re: Stopping my lines from disappearing.

    Okay, but how and where (in which class) do I create the image . Do I use drawImage() to do it?

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,875
    Rep Power
    25

    Default Re: Stopping my lines from disappearing.

    Create a BufferedImage and draw the image on it. Use this forum's Search for examples.
    If you don't understand my response, don't ignore it, ask a question.

  5. #5
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,017
    Rep Power
    6

    Default Re: Stopping my lines from disappearing.

    An alternative is to save the starting an ending points in an array in the mouseListener. Each time paintComponent is called, redraw the lines by iterating thru
    the points. Easiest way to accomplish that would be to create a Line class with starting and ending points. And create an array of that class to hold the lines.

    Regards,
    Jim
    Last edited by jim829; 11-03-2013 at 06:52 PM.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  6. #6
    Melodia is offline Member
    Join Date
    Sep 2013
    Posts
    18
    Rep Power
    0

    Default Re: Stopping my lines from disappearing.

    I solved one problem only to run into another. I have it configured so that the lines don't disappear, but now the white background has been changed to grey.

    Java Code:
    package lineProject;
    
    import java.awt.BorderLayout;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    
    import javax.imageio.ImageIO;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    
    public class DrawingFrame extends JPanel {
    	
    	public static int selectedShape;
    	
    		
    	
    
    	public static void main(String[] args) throws IOException {
    		
    
    		JFrame frame = new JFrame("Test");
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    		frame.setSize(400, 400);
    
    
    		frame.setPreferredSize(new Dimension(400,400));
    		DrawingPanel dp = new DrawingPanel();
    		frame.add(dp,BorderLayout.CENTER);
    
    		
    		frame.pack();
    		frame.setVisible(true);
    
    	}
    	
    
    }
    Java Code:
    package lineProject;
    
    import java.awt.image.*;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.io.File;
    import java.io.IOException;
    
    import javax.imageio.ImageIO;
    import javax.swing.JPanel;
    
    public class DrawingPanel extends JPanel {
    	BufferedImage image;
    	
    
    	public DrawingPanel(){
    		super();
    
    	
    		setSize(400,400);
    		setPreferredSize(new Dimension(400,400));
    		Line line = new Line();
    		add(line);
    		setBackground(Color.white);
    
    		setVisible(true);
    		
    
    	}
    	
    	 public void paintComponent(Graphics g) 
    	  { 
    		    g.drawImage(image, 1000, 1000, null); 
    		   repaint(); 
    	  } 
    	
    }
    Java Code:
    package lineProject;
    
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Point;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    
    import javax.swing.JComponent;
    
    
    public class Line extends JComponent {
    	Point p1,p2;
    	
    	public Line(){
    	
    	addMouseListener(new MouseAdapter() {
         @Override
         public void mouseClicked(MouseEvent e) {
            if (p1 == null || p2 != null) { 
                  p1 = e.getPoint();
                  p2 = null;
              } else {
                 p2 = e.getPoint();
            } 
    repaint();     }
      });
    	setPreferredSize(new Dimension(400,300));}
    	
    	protected void paintComponent(Graphics g) {
          super.paintComponent(g);
         if(p1 != null && p2 != null) {
             g.drawLine(p1.x, p1.y,p2.x,p2.y);
    	
    	
    	
    	}
    		
    	
    	}}
    I can get it back to white by removing the paintComponent method in DrawingPanel, but that just brings it back to the original problem. Transferring the buffered image and paintComponent method from DrawingPad to DrawingFrame doesn't change anything at all. Any ideas as to what might be going on?

  7. #7
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,017
    Rep Power
    6

    Default Re: Stopping my lines from disappearing.

    Create you buffered image and then simply paint the background white. Since you are painting the image over the JPanel, you don't really care what the background color of the JPanel is.

    Also, why is your Line class extending JComponent? All you need for a line is a starting and ending pair of coordinates (and perhaps a color).

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  8. #8
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,875
    Rep Power
    25

    Default Re: Stopping my lines from disappearing.

    Where is the variable: image ever assigned a value?

    BTW Calling repaint() from inside the paintComponent() method makes an infinite loop. repaint() should be called when something new has been created/changed that needs to be drawn.
    If you don't understand my response, don't ignore it, ask a question.

  9. #9
    Melodia is offline Member
    Join Date
    Sep 2013
    Posts
    18
    Rep Power
    0

    Default Re: Stopping my lines from disappearing.

    Are you referring to this part Norm?
    Java Code:
    try {
    			image = ImageIO.read(new File("Image.jpg"));
    		} catch (IOException e) {
    			// Not handled.
    		}
    It was there originally. I must have temporarily taken it out while experimenting.

    And Jim, I don't have a clue how to paint the background white. I thought it would just be a matter of finding an appropriate method from the g. or image. lists, but none of them seem background related. I also tried putting setBackround(Color.white) in various random places, and none of them seemed to have any effect.

  10. #10
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,875
    Rep Power
    25

    Default Re: Stopping my lines from disappearing.

    What happens differently when image has a value?


    Draw a few lines, minimize and restore the frame. What happens?
    Last edited by Norm; 11-04-2013 at 02:56 AM.
    If you don't understand my response, don't ignore it, ask a question.

  11. #11
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,017
    Rep Power
    6

    Default Re: Stopping my lines from disappearing.

    Quote Originally Posted by Melodia View Post
    And Jim, I don't have a clue how to paint the background white.
    Assume you have a buffered image, buf, of size width by height.

    Java Code:
    Graphics g = buf.getGraphics();
    g.setColor(Color.white);
    g.fillRect(0,0,width,height);
    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  12. #12
    Melodia is offline Member
    Join Date
    Sep 2013
    Posts
    18
    Rep Power
    0

    Default Re: Stopping my lines from disappearing.

    Anywhere I I try putting g = image.getGraphics(), I keep getting the same error message:

    at javax.swing.RepaintManager.paintDirtyRegions(Repai ntManager.java:796)
    at javax.swing.RepaintManager.paintDirtyRegions(Repai ntManager.java:769)
    at javax.swing.RepaintManager.prePaintDirtyRegions(Re paintManager.java:718)
    at javax.swing.RepaintManager.access$1100(RepaintMana ger.java:62)
    at javax.swing.RepaintManager$ProcessingRunnable.run( RepaintManager.java:1677)
    at java.awt.event.InvocationEvent.dispatch(Invocation Event.java:251)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.j ava:733)
    at java.awt.EventQueue.access$200(EventQueue.java:103 )
    at java.awt.EventQueue$3.run(EventQueue.java:694)
    at java.awt.EventQueue$3.run(EventQueue.java:692)
    ..........................................
    and various other lines of red text

    I also tried changing it to g=image.createGraphics() because Eclipse recommended it, but that produces the exact same error.

  13. #13
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,875
    Rep Power
    25

    Default Re: Stopping my lines from disappearing.

    The error message does not contain references to method calls in your code. Did you cut off part of the full message?

    Can you post code that compiles, executes and shows the problem?
    If you don't understand my response, don't ignore it, ask a question.

  14. #14
    Melodia is offline Member
    Join Date
    Sep 2013
    Posts
    18
    Rep Power
    0

    Default Re: Stopping my lines from disappearing.

    I had nearly forgotten about this thread, since the due date for the assignment this was part of is long past.

    I couldn't see a difference in performance between when image is assigned a value and when it is not. All except one line will disappear either way. However, since I had to recreate this from this thread, it is quite possible I put that part in the wrong place (directly under the call to super in the panel constructor).

    Here's the whole code for the panel that causes it. the other classes are unchanged.

    Java Code:
    package lineProject;
     
    import java.awt.image.*;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.io.File;
    import java.io.IOException;
     
    import javax.imageio.ImageIO;
    import javax.swing.JPanel;
     
    public class DrawingPanel extends JPanel {
        BufferedImage image;
         
    
    
     
        public DrawingPanel(){
        
     
            super();
            try {
                image = ImageIO.read(new File("Image.jpg"));
            } catch (IOException e) {
                // Not handled.
            }
     
         
            setSize(400,400);
            setPreferredSize(new Dimension(400,400));
            Line line = new Line();
            add(line);
            setBackground(Color.white);
     
            setVisible(true);
             
     
        }
         
         public void paintComponent(Graphics g) 
          { 
                g= image.getGraphics  //This causes a myriad of exceptions
                g.drawImage(image, 1000, 1000, null); 
               repaint(); 
          } 
         
    }
    Just run this to get the innumerable list of exceptions (It is so long that it breaks this forums rules to post the entire thing).

  15. #15
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,875
    Rep Power
    25

    Default Re: Stopping my lines from disappearing.

    Copy the first 30 lines and paste them here.

    On problem I see is that repaint() is called from inside the paintComponent() method. That will cause an infinite loop.
    Every call to repaint() causes a call to paintComponent() which calls repaint() etc

    The Graphics object passed to paintComponent() is the one to use. What is line 43 for?
    If you don't understand my response, don't ignore it, ask a question.

  16. #16
    Melodia is offline Member
    Join Date
    Sep 2013
    Posts
    18
    Rep Power
    0

    Default Re: Stopping my lines from disappearing.

    There are actually less now since I last tried it...
    Not sure how many lines this is.

    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at lineProject.DrawingPanel.paintComponent(DrawingPan el.java:43)
    at javax.swing.JComponent.paint(JComponent.java:1054)
    at javax.swing.JComponent.paintChildren(JComponent.ja va:887)
    at javax.swing.JComponent.paint(JComponent.java:1063)
    at javax.swing.JComponent.paintChildren(JComponent.ja va:887)
    at javax.swing.JComponent.paint(JComponent.java:1063)
    at javax.swing.JLayeredPane.paint(JLayeredPane.java:5 85)
    at javax.swing.JComponent.paintChildren(JComponent.ja va:887)
    at javax.swing.JComponent.paintToOffscreen(JComponent .java:5228)
    at javax.swing.RepaintManager$PaintManager.paintDoubl eBuffered(RepaintManager.java:1508)
    at javax.swing.RepaintManager$PaintManager.paint(Repa intManager.java:1439)
    at javax.swing.RepaintManager.paint(RepaintManager.ja va:1236)
    at javax.swing.JComponent.paint(JComponent.java:1040)
    at java.awt.GraphicsCallback$PaintCallback.run(Graphi csCallback.java:39)
    at sun.awt.SunGraphicsCallback.runOneComponent(SunGra phicsCallback.java:78)
    at sun.awt.SunGraphicsCallback.runComponents(SunGraph icsCallback.java:115)
    at java.awt.Container.paint(Container.java:1967)
    at java.awt.Window.paint(Window.java:3877)
    at javax.swing.RepaintManager$3.run(RepaintManager.ja va:807)
    at javax.swing.RepaintManager$3.run(RepaintManager.ja va:784)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(ProtectionDomain.java:76)
    at javax.swing.RepaintManager.paintDirtyRegions(Repai ntManager.java:784)
    at javax.swing.RepaintManager.paintDirtyRegions(Repai ntManager.java:757)
    at javax.swing.RepaintManager.prePaintDirtyRegions(Re paintManager.java:706)
    at javax.swing.RepaintManager.access$1000(RepaintMana ger.java:62)
    at javax.swing.RepaintManager$ProcessingRunnable.run( RepaintManager.java:1647)
    at java.awt.event.InvocationEvent.dispatch(Invocation Event.java:251)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.j ava:733)
    at java.awt.EventQueue.access$200(EventQueue.java:103 )
    at java.awt.EventQueue$3.run(EventQueue.java:694)
    at java.awt.EventQueue$3.run(EventQueue.java:692)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java: 703)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForFilter(E ventDispatchThread.java:161)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(EventDispatchThread.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:146)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:138)
    at java.awt.EventDispatchThread.run(EventDispatchThre ad.java:91)
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at lineProject.DrawingPanel.paintComponent(DrawingPan el.java:43)
    at javax.swing.JComponent.paint(JComponent.java:1054)
    at javax.swing.JComponent.paintToOffscreen(JComponent .java:5221)
    at javax.swing.RepaintManager$PaintManager.paintDoubl eBuffered(RepaintManager.java:1508)
    at javax.swing.RepaintManager$PaintManager.paint(Repa intManager.java:1439)
    at javax.swing.RepaintManager.paint(RepaintManager.ja va:1236)
    at javax.swing.JComponent._paintImmediately(JComponen t.java:5169)
    at javax.swing.JComponent.paintImmediately(JComponent .java:4980)
    at javax.swing.RepaintManager$3.run(RepaintManager.ja va:796)
    at javax.swing.RepaintManager$3.run(RepaintManager.ja va:784)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(ProtectionDomain.java:76)
    at javax.swing.RepaintManager.paintDirtyRegions(Repai ntManager.java:784)
    at javax.swing.RepaintManager.paintDirtyRegions(Repai ntManager.java:757)
    at javax.swing.RepaintManager.prePaintDirtyRegions(Re paintManager.java:706)
    at javax.swing.RepaintManager.access$1000(RepaintMana ger.java:62)
    at javax.swing.RepaintManager$ProcessingRunnable.run( RepaintManager.java:1647)
    at java.awt.event.InvocationEvent.dispatch(Invocation Event.java:251)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.j ava:733)
    at java.awt.EventQueue.access$200(EventQueue.java:103 )
    at java.awt.EventQueue$3.run(EventQueue.java:694)
    at java.awt.EventQueue$3.run(EventQueue.java:692)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java: 703)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(EventDispatchThread.java:242)
    at java.awt.EventDispatchThread.pumpEventsForFilter(E ventDispatchThread.java:161)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(EventDispatchThread.java:150)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:146)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:138)
    at java.awt.EventDispatchThread.run(EventDispatchThre ad.java:91)

  17. #17
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,875
    Rep Power
    25

    Default Re: Stopping my lines from disappearing.

    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at lineProject.DrawingPanel.paintComponent(DrawingPan el.java:43)
    This is the important one. At line 43 there is a variable with a null value. Find the variable with the null value and then backtrack in the code to see why that variable doesn't have a valid value. If you can't tell, use a println() to print out the variables used on line 43.

    Another problem is the empty catch block. Add a call to the printStackTrace() method to the catch block.
    If you don't understand my response, don't ignore it, ask a question.

Similar Threads

  1. Disappearing Text within a JTextField
    By t338327 in forum New To Java
    Replies: 2
    Last Post: 09-18-2012, 04:07 AM
  2. JTextField Disappearing
    By DinnerFork in forum AWT / Swing
    Replies: 22
    Last Post: 02-13-2012, 04:31 AM
  3. Replies: 3
    Last Post: 10-25-2011, 07:29 PM
  4. Why is javaw.exe Randomly Disappearing
    By Land Of Java in forum JavaFX
    Replies: 0
    Last Post: 10-05-2011, 09:43 PM
  5. Stopping a thread
    By Arne in forum Threads and Synchronization
    Replies: 9
    Last Post: 10-21-2010, 11:26 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •