Please Give Me Your Hands

Here is my codes, I try to save the "drawing" Panel graphics into a jpg, and I can compile it, however, when I run it, system tell me" NullPointerException"!!!
I'm out of ideas, Please help, Thank you So much!!!
import java.awt.*;
import java.awt.image.*;
import javax.swing.*;
import javax.imageio.*;
import com.sun.image.codec.jpeg.*;
import java.io.*;
import java.awt.geom.*;
public class test3 extends JFrame
     public test3()
          super("test");
          setSize(800, 600);
          setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          drawingArea drawing = new drawingArea();
          Container c = getContentPane();
          c.add(drawing, BorderLayout.CENTER);
          int paneWidth = drawing.getWidth();
          int paneHeight = drawing.getHeight();
          BufferedImage buffer = new BufferedImage(600, 600, BufferedImage.TYPE_INT_RGB);
          buffer = (BufferedImage)drawing.createImage(paneWidth, paneHeight);
          Graphics graphic = buffer.getGraphics();
          if(graphic.getClipBounds()!=null)
               graphic.setClip(0, 0, paneWidth, paneHeight);
          drawing.paint(graphic);
          try
               File file = new File("test.jpg");
               FileOutputStream out = new FileOutputStream(file);
               JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
               JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(buffer);
          encoder.setJPEGEncodeParam(param);
          param.setQuality(1.0f,false);
               encoder.encode(buffer);
               out.flush();
               out.close();
          catch(IOException ioe)
               System.out.println(ioe.toString() + "something wrong");
          catch(RasterFormatException rfe)
               System.out.println(rfe.toString() + "rfe");
          setVisible(true);
     class drawingArea extends JPanel
          public void paintComponent(Graphics g)
               Graphics2D g2D = (Graphics2D)g;
               Rectangle2D.Float rect = new Rectangle2D.Float(50F, 50F, 20F, 20F);
               g2D.draw(rect);
     public static void main(String args[])
          test3 t = new test3();
}

1 - the graphics context of a Component is null until the Component is realized, ie, until you call pack or setVisible on its top-level Container
2 - you can make up a BufferedImage and save it without using a Component to show it
3 - using a 'png' extension seems to give better results and a smaller file size than 'jpg'
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import javax.imageio.ImageIO;
import javax.swing.*;
public class ImageTest
    ImageTestPanel imagePanel;
    ImageTestUtility utility;
    BufferedImage image;
    public ImageTest()
        createImage();
        imagePanel = new ImageTestPanel();
        utility = new ImageTestUtility();
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().add(getUIPanel(), "North");
        f.getContentPane().add(imagePanel);
        f.setSize(400,400);
        f.setLocation(200,200);
        System.out.println("imagePanel graphics context before visible = " +
                            imagePanel.getGraphics());
        f.setVisible(true);
        System.out.println("imagePanel graphics context after realized = " +
                            imagePanel.getGraphics());
    private void createImage()
        int w = 200;
        int h = 200;
        image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = image.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setPaint(Color.white);
        g2.fillRect(0, 0, w, h);
        g2.setPaint(Color.blue);
        g2.draw(new Rectangle2D.Double(w/16, h/16, w*7/8, h*7/8));
        int dia = Math.min(w, h)/4;
        g2.setPaint(Color.red);
        g2.draw(new Ellipse2D.Double(w/2 - dia/2, h/2 - dia/2, dia, dia));
        g2.setPaint(Color.green.darker());
        g2.draw(new Line2D.Double(w/16, h*15/16, w*15/16, h/16));
        g2.dispose();
    private JPanel getUIPanel()
        final JButton
            saveComponent = new JButton("save component"),
            saveImage = new JButton("save image");
        ActionListener l = new ActionListener()
            public void actionPerformed(ActionEvent e)
                JButton button = (JButton)e.getSource();
                if(button == saveComponent)
                    utility.saveComponent(imagePanel);
                if(button == saveImage)
                    utility.saveToFile(image);
        saveComponent.addActionListener(l);
        saveImage.addActionListener(l);
        JPanel panel = new JPanel();
        panel.add(saveComponent);
        panel.add(saveImage);
        return panel;
    public static void main(String[] args)
       new ImageTest();
class ImageTestPanel extends JPanel
    public ImageTestPanel() { }
    protected void paintComponent(Graphics g)
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setPaint(Color.red);
        g2.draw(new Rectangle2D.Float(50, 50, 20, 20));
class ImageTestUtility
    public BufferedImage loadImage(String fileName)
        BufferedImage image = null;
        try
            URL url = getClass().getResource(fileName);
            image = ImageIO.read(url);
        catch(MalformedURLException mue)
            System.err.println("url: " + mue.getMessage());
        catch(IOException ioe)
            System.err.println("read: " + ioe.getMessage());
        return image;
    public void saveComponent(Component c)
        int w = c.getWidth();
        int h = c.getHeight();
        BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = bi.createGraphics();
        c.paint(g2);
        g2.dispose();
        saveToFile(bi);
    public void saveToFile(BufferedImage image)
        try
            ImageIO.write(image, "jpg", new File("imageTest.jpg"));
        catch(IOException ioe)
            System.err.println("write: " + ioe.getMessage());
}

Similar Messages

  • Exception when readObj() - please give me a hand!

    I am writing a Client/Server application where Server simply sends object to the client. The first object goes well but when the client side reads the second object, the exception caught was "Type code out of range, is -84". Can anybody kindly give me a hand? Thanks very much in advance!
    Result on Client:
    C:\thesisTest>java TestCli
    @Line 1: Get ready!!!
    Type code out of range, is -84
    receive error.
    Source for Server :
    import java.net.*;
    import java.io.*;
    import java.util.*;
    import sendNode;
    public class TestSer {
         static sendNode sendNodeObj = new sendNode();
    static String inputLine;
         public static void main(String[] args) throws IOException {
    ServerSocket serverSocket = null;
    try {
    serverSocket = new ServerSocket(4444);
    } catch (IOException e) {
    System.err.println("Could not listen on port: 4444.");
    System.exit(1);
    Socket clientSocket = null;
    try {
    clientSocket = serverSocket.accept();
    } catch (IOException e) {
    System.err.println("Accept failed.");
    System.exit(1);
    OutputStream o = clientSocket.getOutputStream();
    ObjectOutput out=new ObjectOutputStream(o);
    BufferedReader in = new BufferedReader(
                        new InputStreamReader(
                        clientSocket.getInputStream()));
    sendNodeObj.sendMsg="@Line 1: Get ready!!!";
    sendNodeObj.typeNode=-1;
    out.writeObject(sendNodeObj);
    out.flush();
    out=new ObjectOutputStream(o);
    sendNodeObj.sendMsg="@Line 2: Please input Start";
    sendNodeObj.typeNode=-1;
    out.writeObject(sendNodeObj);
    out.flush();
    inputLine = in.readLine();
    while (!inputLine.equalsIgnoreCase("Start")) {
         sendNodeObj.sendMsg="@Error, Please input Start";
    sendNodeObj.typeNode=-1;
    out.writeObject(sendNodeObj);
    out.flush();
    inputLine = in.readLine();
    out.close();
    in.close();
    clientSocket.close();
    serverSocket.close();
    Source for Client:
    import java.io.*;
    import java.net.*;
    import java.util.*;
    import java.applet.Applet;
    import sendNode;
    public class TestCli extends Applet {
    static sendNode recNodeObj=null;
    public static void main(String[] args) throws IOException {
    BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
    Socket kkSocket = null;
    PrintWriter out = null;
    try {
    kkSocket = new Socket("127.0.0.1", 4444);
    out = new PrintWriter(kkSocket.getOutputStream(), true);
    } catch (UnknownHostException e) {
    System.err.println("Don't know about host.");
    System.exit(1);
    } catch (IOException e) {
    System.err.println("Couldn't get I/O for the connection to: taranis.");
    System.exit(1);
    InputStream i= kkSocket.getInputStream();
    ObjectInput in= new ObjectInputStream(i);
    try {
         recNodeObj = (sendNode)in.readObject();
    System.out.println(recNodeObj.sendMsg);
         recNodeObj = (sendNode)in.readObject();
    System.out.println(recNodeObj.sendMsg);
    if (recNodeObj.sendMsg.equalsIgnoreCase("@Line 2: Please input Start")) {
    out.println("Start");
    } catch (Exception e) {
    System.out.println(e.getMessage());
    System.out.println("receive error.");
    System.exit(1);
    out.close();
    in.close();
    stdIn.close();
    kkSocket.close();

    You are not being consistent in the way you use ObjectOutputStream and ObjectInputStream.
    For every new ObjectOutputStream you create you need a corresponding new ObjectInputStream, because ObjectOutputStream writes a header that ObjectInputStream reads.
    In general, you probably don't want to use multiple OutputOutputStream objects on a given underlying socket, because it is ineffecient in the way class names etc are encoded.
    Sylvia.

  • Please give me your opinion

    Hi Guys,
    I was wondering if you can give me your opinion about this issue. My friend has a macboobk pro intel core duo 1.83 ghz 512mb ram and 80 gb 15" superdrive and he ask me if I want to trade it for my Macbook 2. ghz Intel core 2 duo , 1gb ram, superdrive, 80gb hd etccc...
    What do you guys think? is it worth it?
    Please advise
    Thanks

    If I were given this option, I'd go with no, only because I've formed an attachment with my macbook.
    However, all the specs on the computers can be upgraded, so if you do choose to make the trade, you can upgrade the memory & ram to your liking, just not the processor speed. If you take an in depth look at the differences between the core duo and the core 2 duo, you might see some that are things you wouldn't want to live without. I've heard that the c2d have the new 802.11n capabilities, while the cd do not. Just something more to take into consideration.
    Personally, I also like the 13.3 inch screen of my macbook (hence why I like it so much) better than the other size screens of other notebooks.
    When I first wanted to get a mac, I was looking at the MBP's, but then I saw the macbooks and my mind was set.
    It is true that your gaming experience and other graphic intensive programs will be better on the mbp, but honestly... I haven't come across anything that runs poorly on my macbook. So... I'd have to go with a no on the trade.
    Just my $.02

  • Please give me your advice

    please explain the concept of  in administration>general settings> inventory planning> backward, forward concept
    can we do the ratio anlaysis  in sap b1 .if we can , please
    explain procedure how we can do it.

    During MRP run system takes into consideration the setting made in administration for inventory planning. Backward planning is general used when - Customer gives you the date of delivery. In such case, you need to plan your activities backward from the date of delivery. Whereas in case of forward planning, you plan when the material can be delivered.
    SAP provides a reporting tool called XL Reporter. Where in you can perform all such activities. Pls go thru the material available on service.sap.com
    Thanks,
    Srikanth

  • Please give me your guide how I can install the purchased program

    today I purchased on your company's website the acrobat program for conversion of pdf files into word or excel file.
    how can i find the program and how can i operate it?

    Hi Adowon,
    If you have purchased Acrobat Pro XI then please go through the given link: http://www.adobe.com/downloads.html?promoid=KAWQL, choose Acrobat from the list of Apps and select try to start downloading. At the time of installation enter the product key to activate it.
    If in case you purchased Acrobat Standard XI retail license then click on the link: https://www.adobe.com/account/account-orders.html#myrecentorders, sign in with your Adobe id and start downloading.
    For Volume licensing purchase log on to www.licensing.adobe.com and donload the software.
    Regards,
    Romit Sinha

  • Please give me your opinion... about tools for develop web service

    If you would like to choose the tool for develop web service.
    what is the most important feature that you will consider,
    Please help me to order these topic from the most to the least
    a. creating web service
    b. creating web service client
    c. searching web service to UDDI registry
    d. publish web service to UDDI registry
    e. connecting to database management systems.
    f. license fee
    g.system requirements
    h. Installation procedures
    thank you very much for your opinion. I will keep your information for my research....
    :)

    Hi Fangnaka,
    You can use JWDSP2.0 + Tomcat 5.X +Jdk1.5 to develop and deploy webservice.
    Better IDEA are Intellij or Eclipse for webservice code development.
    Cheers
    Rajesh R

  • Please give me a hand!!!

    please help me!
    HttpServletRequest request;
    i use "request.setAttribute("value",value);" in a method of "Action" to save the value and use "request.getAttribute("value");" to get the value in "jsp" which findForward from the method, but there are two servers being used which are deployed same. my problem is that when the servers are changing randomly to serve you, can i get the value correctly everytime? if the answer is "no", can you help me solve this problem?
    thank you!
    jjrainbow

    You have two clustered servers, either of which can handle the request?
    As I understand it, once a server receives a request it should handle the entire request. Forwarding to another jsp/servlet is purely an internal transition, and so should not result in changing the server.
    If you can make that assumption, then your request attributes will always be present and correct.
    So I think the answer to your question: "can I get the value correctly every time" is yes. Unless you are doing your own custom clustering which does interfer in the request cycle in which case all bets are off. Most likely though, there is no issue .

  • Hi, I have a MacBook and all of a sudden my screen it froze so I turn it off yes. Now, I cannot turn on my computer even though the battery,it is full charged. Can you please give me your opinions of why this is please? Thank you so very much

    Can you please, anyone tell me your opinion of why all of a sudden my two yr old MacBook was wrking lovely but now I cannot turn it on, even though my battery is fully charged,
    Thank you,
    Isabella

    If Niel's suggestions don't work then also try:
    Intel-based Macs: Resetting the System Management Controller (SMC)
    Resetting your Mac's PRAM and NVRAM

  • IPhoto and Aperture organization please give me your advice

    Well, decided to set up my account here as I see this forum is very helpful.
    I had all my photos organized in Iphoto, but because I bought a camera that shoots Raw decided to get a Aperture to edit my RAW pictures.
    But now I don't know what to do, because I don't want to end up with two libraries to take care, would like something more practical, and also would save space on my
    HD, anyone have any suggestions, how do you organize yourself if you have both?
    Thank you !

    Simply: Use Aperture. It will do just about everything that iPhoto will do, plus has much more powerful editing and organising tools. It is an excellent tool for working with RAWs, whereas iPhoto’s RAW support is pretty much tacked on.
    Then if there is something that iPhoto does that you want, you can share your Aperture Previews into iPhoto (File -> Show Aperture Library) and just darg the pics over.
    Regards
    TD

  • Please give us your opinion: We need your help, Win $100

    Take a moment for the following short survey, in order to help Workshop/WLI
    Tools group with some of the upcoming product decisions?
    You could be the lucky respondent for $100 Amazon Gift Certificate.
    Please take the survey by Friday.
    http://www.surveymonkey.com/s.aspx?sm=rffmcCJ76JK7KzutQ7C9Dw_3d_3d

    1.I have created a down payment request in F-47. When run the APP how to pick that request?
    ANS:  You have to mention the special gl indicator "F" in "spl gl indicators to be paid" under the "vendor's" tab in FBZP.
    2.When run the depreciation for 100 assets, I dont want to calculate & post dep for particular asset, How? Is there any special configuration to do this?
    In AFAB, you can find the button "range" for assets to be considered.
          There you can mention which assets are not be depreciated.
    4.After payment run can we delete the payment proposal? if yes, How?
    ANS:  you can delete the proposal.  But it should be done from the bottom.  That is, first you have delete pmt run and later pmt proposal.
    This can be done in "EDIT" option in menu bar of APP (f110)
    Regards,
    SuryakanthB

  • Please give me your battery life experiences

    Hi there,
    Just got my first Nano. I love the unit itself. The sound far surpasses my expectations and its the first jukebox MP3 I love.. but..
    the battery life is just dreadful for me. I'm getting about 5 hours or so, thats with brightness down, backlight at 2 seconds, and I'm only taking it off hold to change albums or pause! Is this common? If not I will get an exchange, if it is I will just send it back. Disappointing because otherwise it's great!

    I've also had poor battery life until now.
    I tried to switch off certain settings I chose when first configuring the Nano.
    Specifically, I diselected EQ, cross fade and sound check, all in Settings/ Playback.
    I also dimed down brightnes a bit, so it's about a third now (I had it in 50% before).
    I last charged the nano on monday night and I charged it again on wednesday night when it still marked about 10% of the battery charge. So, I had about 48 hours of music and video, not continously of course.
    In total, I must have played like 3 hours of video (games) while listening to music.
    When I had those mentioned playback settings on, the battery would drain in less than 24 hours, so I can tell now how much power they (and probably other settings as well) take from the battery.
    I'm much more satisfied with my purchase now, but I was seriously considering selling the nano and buying either a Classic or a Touch.
    I hope this help other people having short battery life to improve the performance of their nanos. Let us all know how you do.

  • Please Give me your opinion on my website

    Ok first off let me say I am not a professional and am doing
    our webpage on a real low budget because we are a non-profit. I am
    still learning how to use Dreamweaver, but I would love an honest
    opinion about how I am doing. As of now I have a good start on the
    About us section and am slowly working into the others. I just want
    some feedback from some of you about how it looks.
    Thanks in advance for any advice and/or tips you may have.
    www.trnha.org

    It looks okay from here. Anything in particular you're
    concerned about?
    Patty Ayers | Adobe Community Expert
    www.WebDevBiz.com
    Free Articles on the Business of Web Development
    Web Design Contract, Estimate Request Form, Estimate
    Worksheet
    "TracySL80" <[email protected]> wrote in
    message
    news:fjeuhk$su8$[email protected]..
    > Ok first off let me say I am not a professional and am
    doing our webpage
    > on a
    > real low budget because we are a non-profit. I am still
    learning how to
    > use
    > Dreamweaver, but I would love an honest opinion about
    how I am doing. As
    > of
    > now I have a good start on the About us section and am
    slowly working into
    > the
    > others. I just want some feedback from some of you about
    how it looks.
    > Thanks in advance for any advice and/or tips you may
    have.
    >
    > www.trnha.org
    >
    >
    >

  • Give us your feedback on v1.2 of the ILM Assistant

    Please give us your feedback on v1.2
    What would you like us to do next?
    Lilian

    Lillian,
    I had sent you information back on 02/29/2008 as a reply to this thread but it must have got deleted.
    Here is the thread from that day.
    I finally got this to work in my 11g database with Database Vault.
    I got to the ILM login page when I exchanged p=4550:10:2805095104274743
    for p=737677:10:2805095104274743.
    i.e.
    http://oraprod-dr.lodgian.com:8080/apex/f?p=737677:10:2805095104274743
    The documentation for logging into ILM 1.2 seems to be not quite accurate.
    What I saw on that page were 2 boxes:
    1. Database User
    2. Password
    So you actually need to login with a "database" user account.
    Initially I logged in as "SYS" just to see what would happen.
    Then I was able to see the ILM tabs and menus.
    I then went into OEM and created a new database user "ILM_DB_ADMIN".
    I followed the instructions for executing the grant_privs.sql script to that newly created database account.
    I was then able to login with that database account.
    Now the url http://oraprod-dr.lodgian.com:8080/apex/f?p=737677 immediately refers to the ILM login page.
    I would not think that this is a "backdoor" login method into ILM since the documentation does mention that you must use a "database" account.
    Regards,
    Bruce Hawkins

  • Give me your problems

    I would like example problems to learn java better. Please give me your problems and I will solve them- whatever made up thing you can think of, especially if it involves me learning more about the language, constructs, and usage.

    Sounds like what you want is a reference type that can
    be cleared if and only if there are no other
    references to its referent. If I understand the
    current reference types correctly there's no such
    thing. I can't think of anything other than
    maintaining a strong reference or adding something to
    the map as kaj suggested.adding the value to the map wouldn't work because, as hinted
    at by responses to jverd, it is a different map each time ...
    i was thinking of uses hashcodes of the passed maps and when
    they are found to be equal i could perform some further comparison
    somehow; but i suppose the practical side of things is that i want
    all these maps to be uniquely identifiable by their contents, and the
    only way to do that is to save all the data i care about being equal :(

  • Give me your battery life specs

    Got the iPhone 4, not quite as happy with it has I had expected to be. Considering switching to the TB. I hear mized things about the battery--both that it is poor, and also that there are ways to significantly increase battery life. Please give me your specs--how heavily do you use your TB and how long do you get out of a single charge?

    androidburn wrote:
    MostlyALurker wrote:
    Got the iPhone 4, not quite as happy with it has I had expected to be. Considering switching to the TB. I hear mized things about the battery--both that it is poor, and also that there are ways to significantly increase battery life. Please give me your specs--how heavily do you use your TB and how long do you get out of a single charge?
    Everyone's usage is different. For telephone calls only, it is "OK." As a media player, the stock battery is just "OK." Add Internet access, it gets challenging. You can significantly extend the battery life by (a) turning off 4G, (b) spending more money as was probably planned by getting the extended battery which should solve most battery issues entirely. If you turn off 4G, people report life similar to that of a droid x. 
    While there are people that say the phone lasts them through the day, make no mistake, the battery is very poor. HTC plays a regular game by seeing how low capacity of a battery it can put into the phone (this 4G battery actually has 10% LESS power capacity than the 3G Droid X). Like a bullet to the brain that this wouldn't be a great idea.
    Despite all of this, if I had a choice between the iPhone and the Thunderbolt, I wouldn't even consider it a choice. You don't always need 4G but having it is beneficial. If the iPhone isn't for you, I'd say that you'll love having all the neat stuff for Android and not dealing with iTunes, DRM and Apple's limits of the OS for transferring files. If you like the screen size (I do) for text entry, etc. then it's an easy choice right now.
    First, how can you turn off 4G? I thought there wasn't an option for that?
    4G isn't an issue for me---I don't need it. If I could easily turn if off, it would make the TB a lot more appealing to me. I guess what I am really trying to decide is do I:
    a) get the TB and deal with poor battery life, even though the phone is really more than i need
    b) get the Samsung Fascinate even though it is very buggy
    c) cross my fingers and wait until the end of the month until the Incredible 2 is released.
    To do option (c) I would have to return my iphone, revert back to my previous plan and reactivate my bb, and wait another few weeks. Certainly doable but also a hassle.

Maybe you are looking for

  • Performance Report in EM

    Is it possible to produce a performance report of a database in Enterprise Manager over 1 month to 1 year ???

  • HT5621 can't contact Apple support because it's product related

    I wanted to start using iCloud so I clicked on it in Preferences. This led me to having to change my Apple password since it's years since I signed in. I can actually sign in though because my keychain remembers the password, even though I don't. How

  • Workshop generated WSDL.

    In short when I load a WSDL that Workshop generates into XMLSpy , SoapScope , and Cape Clear Studio 4 the file shows up as invalid. So when I tried to generate a WSDL with Cape Clear Studio 4 using the same input and out put parameters for the previo

  • Dvt:shapeAttributes for dvt:areaGraph not working as expected.

    All, This issue is showing up in 11.1.1.6.2. I am attempting to use dvt:shapeAttributes handle events for GRAPH_AREAMAKER for a dvt:areaGraph. I am trying to execute some java code when the mouse is over an area in the areaGraph. The behavior is not

  • How to find imassage

    hello , could someon **** me to find I message on macbook air mountan lion version 10.7.5   thank