How do I save user drawn graphics to a jpeg? (This code doesn't work).

As the title says, I have the code that I think should work but cannot see what is wrong with it:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class SavePaint extends JPanel {
    protected JButton saveButton;
    protected JFrame frame;
    protected int firstX, firstY, currentX, currentY, counter;
    protected JPanel mainPanel = this, panel2;
    protected JButton clearButton;
    protected Color background = Color.PINK;
    protected boolean dragged;
    public SavePaint() {
        JFrame frame = new JFrame("TheFrame");
        frame.add(mainPanel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);
        frame.setVisible(true);
        MyMouseListener myMouseListener = new MyMouseListener();
        mainPanel.addMouseListener(myMouseListener);
        mainPanel.addMouseMotionListener(myMouseListener);
    private class MyMouseListener implements MouseListener, MouseMotionListener {
        public void mouseClicked(MouseEvent e) throws UnsupportedOperationException {
            // code
        public void mousePressed(MouseEvent e) throws UnsupportedOperationException {
            firstX = e.getX();
            firstY = e.getY();
            dragged = true;
        public void mouseReleased(MouseEvent e) throws UnsupportedOperationException {
            currentX = e.getX();
            currentY = e.getY();
            dragged = true;
            repaint();
        public void mouseEntered(MouseEvent e) throws UnsupportedOperationException {
            // code
        public void mouseExited(MouseEvent e) throws UnsupportedOperationException {
            try {
                BufferedImage image = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_INT_RGB);
                Graphics2D graphics2D = image.createGraphics();
                mainPanel.paint(graphics2D);
                ImageIO.write(image, "jpeg", new File("/home/deniz/Desktop/jmemPractice.jpeg"));
            } catch (Exception exception) {
                System.out.println("The exception is: " + exception);
        public void mouseDragged(MouseEvent e) throws UnsupportedOperationException {
            currentX = e.getX();
            currentY = e.getY();
            dragged = true;
            repaint();
        public void mouseMoved(MouseEvent e) throws UnsupportedOperationException {
            dragged = false;
    protected void paintComponent(Graphics g) {
        g.drawLine(firstX, firstY, currentX, currentY);
        firstX = currentX;
        firstY = currentY;
    public static void main(String[] args) {
        new SavePaint();
}An observation that I made is that on top of the white background, there is a dot (is this technically one pixel?) which seems to be the endpoint of what the user (in this case - me) has drawn. The frame has a continous flow of dots display as the user makes them with the cursor. Why isn't the jpeg a continuous flow of dots as well?
Any help would be greatly appreciated!
Thanks in advance!

there is a dot (is this technically one pixel?) This shows a problem with your painting logic.
Whenever the panel is repainted, you only have a single line of code, so only a single pixel is ever drawn. The drawing looks like its working because Swing hasn't asked the panel to repaint itself so you see the cummulative effect of all your drawLine(...) method.
However, try drawing a few lines, then minimize the window and then restore the window. You will only see a single pixel. This is exactly what you see when you try to create the jpeg.
You should probably be using the "Draw on Image" approach suggested in [url http://www.camick.com/java/blog.html?name=custom-painting-approaches]Custom Painting Approaches.
Just for interest sake you can also use the ScreenImage class I suggested to you earlier in your other posting (when you didn't bother to accept the answer I provided, so this will be the last time I help if you don't learn to use the forum properly).
ScreenImage.writeImage(ScreenImage.createImage((Component)mainPanel), "mainPanel.jpg");This will force the class to use the Robot to capture the actual pixels on the screen. Using a Robot is slower then using the paint() method.

Similar Messages

  • How do I save a freeze frame as a jpeg photo?

    How do I save a freeze frame as a jpeg photo? I tried right clicking it and copy but it won't paste to iPhoto.

    Skunkboat wrote:
    ...  I know people say that Apple doesn't even look at these posts (on THEIR website). I can't imagine that ...
    if you have a suggestion, contact Apple direct:
    http://www.apple.com/feedback/imovie.html
    This is meant as a user2user-board ... no use for a company to dig thru this pile of complains repetitive posts ...
    speaking of FAQ, there's a section for that either, User Tipps:
    How can I make a still frame from iMovie 11? (also works in iMovie 10)

  • Can anyone tell me how I can save a password again after "never remind this password" was pressed accidentally

    Can anyone tell me how I can save a password again after "never remind this password" was pressed accidentally

    More details please.  In what application did this happen?

  • How to use documentbeforesaved method? And why my code doesn't work in template files?

    Can someone help me with these two codes?
    ----Beginning of code 1-------------
    Private WithEvents App As Word.Application
    Private Sub Document_Open()
    Set App = Word.Application
    End Sub
    Private Sub App_DocumentBeforeSave(ByVal Doc As Document, SaveAsUI As Boolean, Cancel As Boolean)
    MsgBox("BeforeSave")
    End Sub
    --------------End of the code----------------
    Beginning of code 2--------------- Code 2 is from https://msdn.microsoft.com/en-us/library/office/ff838299(v=office.15).aspx
    Public WithEvents appWord as Word.Application 
    Private Sub appWord_DocumentBeforeSave _ 
     (ByVal Doc As Document, _ 
     SaveAsUI As Boolean, _ 
     Cancel As Boolean) 
     Dim intResponse As Integer 
    Private Sub App_DocumentBeforeSave(ByVal Doc As Document, SaveAsUI As Boolean, Cancel As Boolean)
    MsgBox("BeforeSave")
    End Sub
    In the first code, they have:
    Private Sub Document_Open()
    Set App = Word.Application
    End Sub
     I test these two codes in "This document" object, and I find out the first code works but the second code are not!
    Why second code doesn't work?
    Extra question: I am using microsoft 2013. I insert this code into a macro-enabled template. But when I am about to save my file I am expecting these code works. However, they didn't work!
    Thank you for solving these problem for me!

    Hello,
    Please note that the code snippet 2 in your post is different from the code snippet in the MSDN document. Also please read the comments of the MSDN code sample:
    This example prompts the user for a   yes or no response before saving any document.
    This code must be placed in a   class module, and an instance of the class must be correctly initialized to   see this example work; see
    Using Events with the Application Object for   directions on how to accomplish this.
    Public WithEvents appWord   as Word.Application
    Private Sub   appWord_DocumentBeforeSave _
     (ByVal Doc As Document, _
     SaveAsUI As Boolean, _
     Cancel As Boolean)
     Dim intResponse As Integer
     intResponse = MsgBox("Do you really   want to " _
     & "save the document?", _
     vbYesNo)
     If intResponse = vbNo Then Cancel = True
    End Sub
    So the problem in your code snippet 2 is that you didn't put it into a class module and initialize the class module. If you just put it into ThisDocument, you have to initialize the word application object.
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • ITunes 10.4.1.10 how to stop downloads of free news pods?  (right click delete doesn't work) also can't scroll down list of downloads!

    (ITunes 10.4.1.10) How to stop downloads of free news pods?  (right click delete doesn't work)
    Also can't scroll down list of downloads so as to pause them.  Would like to delete them as ISP has download limit.
    Thanks in advance!  (this seems to be a dumb problem of the software having a life of its own!)

    I have been talking to Apple support about this very problem. So far they have asked me to disable both Firewall and Anti Virus software (Windows Firewall and ESAT NOD32 anti virus) - this didn't work. Rebuild my library - this didn't work. Un-install all Apple applications and re-install - this didn't work. I have created a second user account on my PC and from that account (both accounts set as Administrator) I can activate Genius. This suggests to me that the problem is possibly linked to my original User Account, which is the one I always use. I am waiting for the next update from Apple and will post an update if/when the problem is resolved.
    What I also notice is about 2 seconds in to Step 2 of the Genius activation, the progress diagonal lines bar stops, and then starts again. As soon as I see this short freeze I know that the activation will fail.

  • I have Iphone 4G. I bought when I studied in Usa. Then I returned to  Uzbekistan this Iphone doesn't work. How I can use this phone? Can you help me?

    I have Iphone 4G. I bought when I studied in Usa. Then I returned to  Uzbekistan this Iphone doesn't work. How I can use this phone? Can you help me?

    shohjahon wrote:
    I have Iphone 4G.
    No, you do not.  It simply is not possible to have a device that does not exist.
    Most likely, you have an iPhone 4.  There is no 4G iPhone.
    shohjahon wrote:
    I bought when I studied in Usa. Then I returned to  Uzbekistan this Iphone doesn't work.
    Yes, it does work.  It is carrier locked to AT&T, just like all GSM iPhones sold in the US since their introduction.
    shohjahon wrote:
    How I can use this phone?
    You can use the phone as it is, but it will be very expensive with AT&T international roaming plans.
    There is no official way to unlock the phone for use with another carrier.
    Your options:
    Sell the device and purchase one intended for use in your country.
    Find unofficial method to unlock
    Use as an iPod Touch.
    No one here can provide you with assistance on getting you AT&T locked iPhone to work on another carrier.

  • HT1977 How do i get my money back for an app if it doesn't work?

    How do i get my money back for an app if it doesn't work?

    With every purchase you'll receive an email confirmatiom. There is a link: "Report Problem". Use it.

  • The bottom bar on my mail has disappeared which means I can't create, reply or forward to an email. Any ideas how to get it back? Touching the screen at the bottom doesn't work!

    The bottom bar in my email seems to have disappeared which means I can't create, reply or forward any emails. Any auggestions to how to get it back? Touching the bottom of the screen doesn't work. Thanks.

    Close all apps in the Multitasking Drawer; Double Tap Home Button to open drawer, Swipe up on each app to close it. Repeat until all apps are closed, touch home screen.
    Restart phone, hold both Home and Power/Sleep buttons down at the same time, continue to hold them down until the Apple Logo appears, Release both buttons and wait for phone to restart.
    Check email app to see if bottom bar and new email icon have come back.
    If not, delete the email account in settings and then add it back in again.
    If mail still not working as it should, you may try doing a Reset All Settings reset in Settings => General => Reset => Reset All Settings.  You won't lose any data, music, apps, videos,pictures, etc.  But you will have to go back in and turn on or off any settings you changed on your phone because everything will be set back to factory defaults.

  • HT1918 I changed the card and i want to know how make to change the data from itunes. I tried and doesn't work.

    I changed the card and i want to know how make to change the data from itunes. I tried and doesn't work. Please, Help Me!

    No. That's not what I said. You can get an out of warranty replacement, which will be exactly the same model, color, and will be locked in exactly the same way the original is. If you want an iPhone 5, get the 4S replaced, sell it, and use the money to put toward a new phone.

  • How can I fix my search engine? Google, Yahoo and Bing doesn't work.

    How can I fix my search engine? Google, Yahoo and Bing doesn't work. I try to change them and they doesn't work. Its there a way to fix this problem?

    Power off the router. Unplug it from the wall. Wait for few  minutes.
    Power off the router. Wait a while.
    Connect the router back to to the wall.
    Power the router back on. Wait  until all lights are lit properly. It will take a while.
    Restart the computer.
    Start up in Safe Mode.
    http://support.apple.com/kb/HT1455

  • HT4623 if the phone we are updating is locked how can we 6.1 to 5.0 and what if restoring doesn't work at all...

    if the phone we are updating is locked how can we 6.1 to 5.0 and what if restoring doesn't work at all...

    iTunes will only ever install the latest version of iOS for the device, in the case of the 3GS that is 6.1.

  • Upload file jsp code doesn't work? How can I debug

    Hi Everyone,
    I have the following jsp code that simply adds a new product to the backend database when 'Continue' button is pressed.
    if( "Continue".equals(fp.getParameter("Submit")) ) {
         fp.setParameters(prodForm);
         prodForm.setCreateBy(currentUser.getUserID());
         prodForm.save();
         String filename = fp.getFilename("file");
              if( filename != null ) {
              // a file was uploaded
              // set the path to save it
              fp.setFilePath(PHYSICAL_PATH + "uploads\\");
              // we will change the filename to make sure it is unique
              // need to keep the file type
              String fileType = "";
              try { fileType = filename.substring( filename.lastIndexOf(".") ).toLowerCase(); }
              catch( Exception e ) { fileType = ""; }
              fp.saveFile("file", "POS_" + prodForm.getProductID() + fileType);
              prodForm.setSketch("POS_" + prodForm.getProductID() + fileType);
              prodForm.save();
         db.close();
         response.sendRedirect("index.jsp");
         return;
    }The code works fine but the upload doesn't work. This is the upload part of the above code:
    String filename = fp.getFilename("file");
              if( filename != null ) {
              // a file was uploaded
              // set the path to save it
              fp.setFilePath(PHYSICAL_PATH + "uploads\\");
              // we will change the filename to make sure it is unique
              // need to keep the file type
              String fileType = "";
              try { fileType = filename.substring( filename.lastIndexOf(".") ).toLowerCase(); }
              catch( Exception e ) { fileType = ""; }
              fp.saveFile("file", "POS_" + prodForm.getProductID() + fileType);
              prodForm.setSketch("POS_" + prodForm.getProductID() + fileType);
              prodForm.save();
         db.close();
         response.sendRedirect("index.jsp");So if the file browser, <input type="file" name="file">, has a file, then it saves the file in the upload folder and saves the filename in the database. But it doesn't work, it doesn't save the file in the upload folder nor it saves the filename in the database. I am new to java and jsp so could you tell me what error checking or deguging I can do in jsp to spot the problem.
    Thanks,
    Zub

    where u write the code to upload the file
    to server end?

  • HT1430 How do you turn off your phone if the sleep/wake button doesn't work anymore?

    How do you turn off your phone if your sleep/wake button doesn't work anymore?

    If a reset doesnt fix it (which it wont - that is likely a hardware issue), then get warranty service.
    http://www.apple.com/support/contact/
    1-800-MY-APPLE (1-800-692-7753)

  • HT201263 how can i go to DFU mode if my sleep/wake button doesn't work? my phones been stuck on the logo for too long.

    how can i go to DFU mode if my sleep/wake button doesn't work? my phones been stuck on the logo for too long.

    You can't. Either get your phone fixed at a third-party repair shop, or go to an Apple store & they will replace your phone for US $199.

  • How i am suppose to receive my iCloud username if the email doesn't worked?

    how i am suppose to receive my iCloud username if the email doesn't worked?
    the email that they have is not the right one because my real one didn't worked so i created one and they send me all the information about how to change my email for a username in a other email who works (my real one).but now i am suppose to receive a email as they said but i don't...
    how i am suppose to get the information if the email don't work?
    thanks
    (i french sorry for my horrible english)

    See if Apple ID Support can help.
    There is a contact link.
    Apple ID Support

Maybe you are looking for