JScrollPane, JPanel used to make a paint-like application

I am new to swing. I need help with implementing a paint-like application using JScrollPane and JPanel.
I have put a JPanel inside a JScrollPane.
The size of JPanel exceeds preferred size of JScrollPane, and i can see the scrollbars, and can go up and down.
Problem is, when i draw on the JPanel, i can see what i've drawn very clearly. Now if I scroll down, and then scroll back up, whatever i had previously drawn has been erased.
let me put it in a simpler manner. suppose i have drawn a filled circle whose diameter is equal to the viewport size of the JScrollPane. Now i am scrolling down till i can see only the bottom half of the circle. When i scroll back up, the upper half of the circle has been erased.
i think this is a newbie error, and i guess it'll have a textbook response, so i have not bothered to paste my entire code here. however, if it is required, please let me know.

Sounds very much like you're painting outside the paint cycle. Read this,
http://java.sun.com/products/jfc/tsc/articles/painting/
When the user draws on the screen, you want to do one of two things (these being just the most obvious and easiest implementations). For raster operations you want to manipulate an Image; for vector operations you want to manipulate a collection of Shapes.
Your paintComponent() method of the panel should simply draw the stored images and shapes to the supplied Graphics object as appropriate.
If you paint to a Graphics object outside the paint cycle then it will all be erased when the paint cycle is next invoked.

Similar Messages

  • A "Paint like" application

    Hi,
    I'm currently programming an application for my sister and I would like to finish before Christmas, but I'm really late. So to complete a part of it, I'm looking for the source of a paint like application. Just something you use to draw line, circle, rectangle, filling it or not, choosing the color... So If you can give me a link to this kind of source, or post some source It would be great.
    Thank you.
    S�bastien

    With a fill option.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.awt.image.*;
    import javax.swing.border.*;
    public class PaintLike extends JFrame  implements ActionListener
         PPanel  panel  = new PPanel();
         JPanel  contr  = new JPanel();
         PButton whatt;
         JLabel  whatc;
    public PaintLike()
         addWindowListener(new WindowAdapter()
         {     public void windowClosing(WindowEvent ev)
              {     dispose();
                   System.exit(0);
         setResizable(false);
         setBounds(10,10,780,500);
         getContentPane().add("Center",panel);
         getContentPane().add("West",contr);
         contr.setLayout(new BorderLayout());
         Border       br = BorderFactory.createEtchedBorder(EtchedBorder.LOWERED,Color.white,Color.gray);
         contr.setBorder(br);
         contr.add("North",addButtons());
         contr.add("Center",new JPanel());
         contr.add("South",addColors());
         setVisible(true);
         panel.requestFocus();
    private JPanel addButtons()
         JPanel panel = new JPanel();
         panel.setPreferredSize(new Dimension(70,175));
         panel.setLayout(new GridLayout(5,2,1,1));
         for (int i=0; i < 10; i++)
              PButton jb = new PButton(i);
              jb.addActionListener(this);
              panel.add(jb);
         return(panel);
    private JPanel addColors()
         JPanel panel = new JPanel();
         panel.setLayout(new BorderLayout());
         JPanel canel = new JPanel();
         panel.add("North",canel);
         canel.setLayout(new GridLayout(5,4,0,0));
         canel.setPreferredSize(new Dimension(70,90));
         Color[] colors = {Color.black,Color.blue,
                               new Color(152,0,0),new Color(132,66,0),
                               Color.cyan, new Color(219,219,112),
                               Color.gray,Color.green,
                               new Color(200,200,200),
                               Color.magenta,new Color(0,0,108),
                               Color.orange,Color.pink,
                               Color.red,new Color(155,192,210),
                               new Color(230,230,230),new Color(64,224,208),
                               Color.white,Color.yellow};
         for (int i=0; i < colors.length; i++)
              JButton jb = new JButton("");
              jb.setBackground(colors);
              jb.addActionListener(this);
              jb.setRequestFocusEnabled(false);
              canel.add(jb);
         whatc = new JLabel(" ");
         whatc.setOpaque(true);
         whatc.setBackground(Color.blue);
         whatc.setBorder(new MatteBorder(1,1,1,1,Color.black));
         panel.add("Center",whatc);
         return(panel);
    public void actionPerformed(ActionEvent ae)
         if (ae.getSource() instanceof PButton) whatt = (PButton)ae.getSource();
         else if (ae.getSource() instanceof JButton)
              whatc.setBackground(((JComponent)ae.getSource()).getBackground());
    public class PPanel extends JPanel implements MouseMotionListener, MouseListener
         Point mp,fp,tp;
         Vector objects = new Vector();
         BufferedImage image;
         Graphics2D graph;
    public PPanel()
         setBackground(Color.white);
         addMouseMotionListener(this);
         addMouseListener(this);
    public void paintComponent(Graphics g)
         super.paintComponent(g);
         if (image == null || image.getWidth(null) != getWidth() ||
                             image.getHeight(null) != getHeight())
              image = (BufferedImage)createImage(getWidth(),getHeight());
              graph = (Graphics2D)image.getGraphics();
              graph.setColor(Color.white);
              graph.fillRect(0,0,getWidth(),getHeight());
              for (int i=0; i < objects.size(); i++)
                   PObject po = (PObject)objects.get(i);
                   po.draw(graph);
         g.drawImage(image,0,0,null);
         g.setColor(whatc.getBackground());
         if (whatt != null && fp != null)
              if (whatt.type == 0) g.drawLine(fp.x,fp.y,tp.x,tp.y);
              if (whatt.type == 1) g.drawOval(fp.x,fp.y,tp.x-fp.x,tp.y-fp.y);
              if (whatt.type == 2) g.drawRect(fp.x,fp.y,tp.x-fp.x,tp.y-fp.y);
    public void mouseDragged(MouseEvent m)
         if (whatt == null) return;
         if (whatt.type > 2) return;
         if (fp == null)
              fp = new Point();
              tp = new Point();
         if (whatt.type == 0)
              fp.setLocation(mp.getLocation());
              tp.setLocation(m.getPoint().getLocation());
         else
              fp.x = Math.min(mp.x,m.getX());
              fp.y = Math.min(mp.y,m.getY());
              tp.x = Math.max(mp.x,m.getX());
              tp.y = Math.max(mp.y,m.getY());
         repaint();
    public void mouseMoved(MouseEvent m){}
    public void mouseClicked(MouseEvent m)
    //     if (whatt.type == 6)
    //          fillIt(mp.x,mp.y,image.getRGB(mp.x,mp.y));
    //          changeMx(image.getRGB(mp.x,mp.y),mp.x,mp.y);
    //          repaint();
    public void mouseEntered(MouseEvent m){}
    public void mouseExited(MouseEvent m) {}
    public void mouseReleased(MouseEvent m)
         if (whatt == null) return;
         if (whatt.type == 6)
              fillIt(mp.x,mp.y,image.getRGB(mp.x,mp.y));
              repaint();
              return;
         if (fp != null)
              PObject po = new PObject(whatt.type,fp,tp,whatc.getBackground());
              objects.add(po);
              po.draw(graph);
              fp = null;
    public void mousePressed(MouseEvent m)
         mp = m.getPoint();
    public void fillIt(int x, int y, int ogb)
         int ng = whatc.getBackground().getRGB();
         if (ng == ogb) return;
         int[] xv = new int[getWidth()*getHeight()];
         int[] yv = new int[getWidth()*getHeight()];
         int ii = 1;
         image.setRGB(x,y,ng);     
         xv[0] = x;
         yv[0] = y;
         for (int i=0; i < ii; i++)
              int xx = xv[i];
              int yy = yv[i];
              if (xx > 0 && image.getRGB(xx-1,yy) == ogb)
                   xv[ii] = xx-1;
                   yv[ii] = yy;
                   image.setRGB(xx-1,yy,ng);
                   ii++;
              if (yy > 0 && image.getRGB(xx,yy-1) == ogb)
                   xv[ii] = xx;
                   yv[ii] = yy-1;
                   image.setRGB(xx,yy-1,ng);
                   ii++;
              if (xx < getWidth()-1 && image.getRGB(xx+1,yy) == ogb)
                   xv[ii] = xx+1;
                   yv[ii] = yy;
                   image.setRGB(xx+1,yy,ng);
                   ii++;
              if (yy < getHeight()-1 && image.getRGB(xx,yy+1) == ogb)
                   xv[ii] = xx;
                   yv[ii] = yy+1;
                   image.setRGB(xx,yy+1,ng);
                   ii++;
    public class PButton extends JButton
         int type;
    public PButton(int type)
         this.type = type;
    public void paintComponent(Graphics g)
         super.paintComponent(g);
         Graphics2D g2 = (Graphics2D)g;
         g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
         g2.setStroke(new BasicStroke(1.2f));
         if (type == 0) g.drawLine(8,8,getWidth()-10,getHeight()-11);     
         if (type == 1) g.drawOval(6,10,getWidth()-13,getHeight()-20);
         if (type == 2) g.drawRect(7,7,getWidth()-15,getHeight()-14);
         if (type == 6) g.drawString("Fill",7,20);
         if (hasFocus())
              g.setColor(Color.gray);
              g.drawRect(4,3,getWidth()-9,getHeight()-7);     
    public class PObject extends JComponent
         int type;
         Point fp,tp;
         Color color;
         boolean fill;
    public PObject(int type, Point fp, Point tp, Color color)
         this.type = type;
         this.fp = fp;
         this.tp = tp;
         this.color = color;
    public void setFill(boolean fill)
         this.fill = fill;
    public void draw(Graphics g)
         g.setColor(color);
         if (type == 0) g.drawLine(fp.x,fp.y,tp.x,tp.y);
         if (type == 1) g.drawOval(fp.x,fp.y,tp.x-fp.x,tp.y-fp.y);
         if (type == 2) g.drawRect(fp.x,fp.y,tp.x-fp.x,tp.y-fp.y);
    public static void main (String[] args)
         new PaintLike();
    Noah

  • Is there a windows "paint" like application on my macbook?

    if anyone has any tips, id appreciate the knowledge.

    I downloaded several different programs and ended up deleting them all. I could not find one that worked as well as MSPaint. which is sad since wasn't the original 1984 mac known for its paint like program-- GUI interface and all.
    I wanted to take several pictures of the apple logo and put all of them on my desktop as the background and sadly I had to use a windows machine and used paint to do it.
    "My screen name is don't make me switch back, so don't make me answer my questions and tell me why mac is better."

  • How to make a HyperCard-like application

    I've written several japplets that do useful things, but they have been "single-screen" applications. This time I have to program a japplet that has multiple screens. On the 1st screen, the user makes a selection. Upon hitting "Next", the 2nd screen appears, where he does something else, etc. etc. Much like a HyperCard or Macromedia Director kind of program. Could somebody help me get started? I thought of making a JPanel for each "screen". But how do I switch from one JPanel to the next? Any help would be much appreciated!

    CardLayout

  • "Paint" like Application?

    I looked under Downloads and I couldn't find anything that I was looking for.
    I am looking for an Application something like Paint in Microsoft. Where I can add a text box, etc. Things of that nature.
    Any suggestions on what Applications would fulfill this?
    Thanks

    It depends on the complexity. While "Paint" will allow you to use editing tools such as the pencil, which change the individual pixels on the image, Apple's "Preview" application does allow you to add markup and annotations to certain files. You will have to first save pictures as a PDF, and then open them in preview again to add ovals, rectangles, text, and whatnot using the "Tools" menu. Then you can export the results in an image format such as JPG or PNG. It's a little more involved in this sense, but can be done without third-party software if a simple text box or oval-like markup is all you want to do.

  • What do you use to make Gnome apps look good in KDE4?

    What are you all using to make Gnome apps (like Firefox, Gimp, Inkscape.. etc) look good in KDE (I am using KDEmod).
    I tried Qtcurve (I think it works the best), gtk-qt-engine (for some reason it didn't seem to work for me) and others...
    I want to hear opinion from other people (who use KDE or possibly KDEmod) and who are probably using Arch longer than me. This is my first successful Arch install.
    Last edited by kdar (2009-12-15 03:07:05)

    +1 for qtcurve
    yes.. i need to rebrand the startmenu icon....
    Last edited by Rasi (2009-12-15 07:06:46)

  • On my iPhone 4, people cant hear me when I make and / or receive normal (GSM) phone calls. But when on calls using internet based / native apps like viber or skype, people can hear me just fine. Voice memos work too and have already tried different SIMs

    On my iPhone 4, people cant hear me when I make and / or receive normal (GSM) phone calls. But when I make/receive calls using internet-based / native apps like viber or skype, people can hear me just fine. I have tried recording my voice using voice memos - this works. And have already tried different SIM cards but the problem persists.
    I have taken my phone to an authorized Apple service center, where they restored my phone to factory settings, but still facing the same issue. They service center directed me to Apple Customer Care Hotline, where I have now spent 3+ hours explaining my issue and yet no one can resolve it. The easy answer if to replace the phone - and since it is out of warranty, I am expected to pay for it.
    Additionally, the customer service has been so rude and confrontational that it has completely changed my view of Apple and its customer focus. I am a disappointed and angry customer today - people would be surprised to hear just how rude customer service was including making statements such as "Apple doesnt make infallible products, that's why warranty is needed for our products" and that "every product undergoes a problem at some stage, so do ours!" There goes whatever confidence I had...
    My concern is simple - if no one at Apple and / or its CS hotline is able to address my issue comprhensively and keep telling me that they have never encountered a precedent before, then with what right can they expect me to pay for a replacement?! I am NOT here to fund Apple's research into their product faults and manufacturing.
    And even though a customer is out of warranty, is it too much to expect an Apple product to work well for at least a 'reasonable' period of time. My phone is less than 18 months old and has been facing this issue for the past 2 months - surely the longevity of Apple products is more than 18 months!
    Just a sad sad day for an Apple customer, compounded by unjustifiably rude and aggressive staff. And still no resolution to my problem.

    I am having the same issue - with my last 2 iPhone 4's. My first handset each time I was on a call wether it was up to my ear or on loud speaker, the call would automatically mute even though the mute button wouldn't show up as highlighted. Pressing the mute button on and off during the call doesn't fix it either. I rang Apple and asked what some of their trouble shooting solutions were. I got told that it might be a software issue and to install the latest software update. This failed. I then got told to uninstall the software on the phone and do a complete restore. This also failed. After trying the troubleshooting suggestions, I took the phone into my provider and they sent me out a new phone within a week under warranty claiming it was a hardware issue and probably just a "glitch" with that particular phone. This was not the case....
    After receiving my second iPhone 4, I was hopeful that it would work. For the first couple of days, making/receiving calls was not an issue. Until after about a week, the same problem started again. In one instance I had to hang up and call back 4 times and the call would still automatically mute after about 5 seconds. Also on the second handset, the main camera located on the back of the phone has red and blue lines running through it and can't take a decent picture. So back to the store I go to get another replacement - Again.
    For a phone that is rated highly and as a keen Apple product purchaser, I am a bit disappointed with the experience I have had with the iPhone 4. Let's hope they find a fix sometime soon because this is becoming a bit beyond a joke.....!!

  • I used to make booklets on Publisher that would be printed on 11X17 folded and stapled down middle.  Can someone please tell me best program to create a document like this in on a mac and how to print it on 11X17?

    I used to make booklets on Publisher that would be printed on 11X17 then be folded and stapled down middle.  Can someone please tell me best program to create a document like this in on a mac and how to print it on 11X17?

    Try iStudio Publisher

  • What app do people use to make their pictures look like this

    what app do people use to make their pictures look like this?

    Apparently redchainsaw answered back saying that wasn't it. Though looking at the pictures I see nothing odd or special about them.
    With that said however, there are many image editors in the App store, and the Instagram App does have several filters you can apply to the photos.   So its very possible that is it.

  • I have one folder with several projects all of which Aperure can not find the original.  I do not use referenced files.  I can't make any adjustments like cropping etc. What can I do to print any of these photos?

    I have one folder with several projects all of which Aperure can not find the original.  I do not use referenced files.  I can't make any adjustments like cropping etc. What can I do to adjust or print any of these photos?  IO have no ther projects with this problem.  My Aperture Library is automatically saved to two external drives.
    Dick Koos

    I have one folder with several projects all of which Aperure can not find the original.
    Have you checked inside your Aperture library, if the original files are still there?
    Try to find out, when the images in those projects have been originally imported, then open the Aperture library by ctrl-clicking it and using the command "Show package contents" from the pop-up menu. In the window that will open, select the folder "Masters" and browse the contents. You need to find the subfolder with the year you imported the images, then the folders with the month and the day.
    Are your original files still there?
    If yes, copy them to a folder on your desktop for safe-keeping, and then try, if repairing the permissions and the other Furst Aid tools will help Aperture to connect to these missing files again - see this link:  Repairing and Rebuilding Your Aperture Library: Aperture 3 User Manual
    If the First Aid Tools don't help, then check, if Aperture has moved the missing images to a "recovered folder". If not, reimport the images, you saved to your Desktop and use the Lift&Stamp tool to transfer any adjustment and captions to your reimported images.

  • What does Apple site use to compress the videos to make it look like DVD?

    What compression program do they use for videos on apples site to compress these videos. They look crisp like DVD Quality? How and what kind of settings do they use?
    My videos look like crap after being compressed and even crappier once uploaded on YouTube.
    I used H.264 800Kbps Streaming in Compressor 3 to compress.
    Camera used: Canon XL2 with 16:9, 24p.
    NLE's used: FCP or Avid MC3.
    Guys, how can I make my videos look as good as DVD while keeping the size low.
    How should I set my properties?
    Is their a tutorial on the web?
    Someone please help!
    Thanks,
    Zia

    http://www.kenstone.net/discussions/read.php?3,8699,8699#msg-8699

  • HT201365 I hate the look of ios 7.0.2. can I make it look like it used to?

    I hate the look of ios 7.0.2. can I make it look like it used to?

    No.
    I'm sorry, but Apple does not provide a downgrade path for iOS. Because downgrading is unsupported by Apple we cannot discuss it on these forums.
    You may leave comments at Apple Feedback.

  • I used to be able to make FF look like IE with a button. I don't see the button anymore.

    Some sites require IE e.g. Microsoft Update. I can't figure out how to make FF look like IE the way I used to do.
    Bill

    Did you have an add-on such as [https://addons.mozilla.org/en-US/firefox/addon/92382/ IE Tab 2 (FF 3.6+)] or [https://addons.mozilla.org/en-US/firefox/addon/10909/ IE Tab Plus (FF 3.6+)].

  • What sound filter to use to make a mans voice sound like he's outside.

    Hello, I have several ADR files of people talking. I need to add a filter to make it sound like they are talking outside. Any specific suggestions would be greatly appreciated.

    Try something like this, adjust to taste:
    Note that this will drop the volume of the track substantially, you will need to adjust the clip level after you've applied the effects.
    MtD

  • Resizing JPanels using a mouse?

    I have a program that draws on a BufferedImage, but I want to be able to resize the image. At the minute it is on a JPanel, which in turn will be placed in a JScrollPane, but I was wondering if there was a way of resizing the JPanel using the mouse, like you can with a JFrame.
    If not, is there another way I can do this?
    Thanks in advance.

    Thanks for the replies so far.
    I'm trying to write a basic drawing program, and the plan was that the image size (and also its observer component) are not fixed and are independent of the frame (or other component) in which they are located. That was where I assumed the JScrollPane would come in, as this way all the image can be accessed if I make the main window small, for example.
    I've not had a lot of experience doing this kind of thing though, so I'm still not sure of the best way to go about it. As I see it, the JSplitPane is only resizable in one axis. A JSplitPane can effectively be resized in both axes by nesting JSplitPanes, but I feel that this will look a bit untidy.

Maybe you are looking for