In paintImmediately null graphics

This message comes from the _paintImmediately method of JComponent but I'm not sure of the cause.  I don't see any exception stack trace and so I can only assume that SwingGraphics.createSwingGraphics(Graphics g) is returning a null Graphics object even though the Graphics object passed in is non-null.
Any ideas? Anyone? Bueller? Bueller?

Okay managed to stop my program throwing this error. For some reason I had a revalidate() in the middle of my processing code and not on the Event Thread. Still unsure as to why it only was an issue only on the second call but there we go.
Thanks

Similar Messages

  • Null graphics error

    While clicking on some button, two tables along with values are displayed as results.
    If i try to run continuosly, the following error was obtained.
    java.lang.Exception: Stack trace
         at java.lang.Thread.dumpStack(Unknown Source)
         at javax.swing.SwingGraphics.createSwingGraphics(Unknown Source)
         at javax.swing.JComponent._paintImmediately(Unknown Source)
         at javax.swing.JComponent.paintImmediately(Unknown Source)
         at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
         at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown Source)
         at java.awt.event.InvocationEvent.dispatch(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    java.lang.NullPointerException
         at javax.swing.JComponent._paintImmediately(Unknown Source)
         at javax.swing.JComponent.paintImmediately(Unknown Source)
         at javax.swing.RepaintManager.paintDirtyRegions(Unknown Source)
         at javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown Source)
         at java.awt.event.InvocationEvent.dispatch(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    In paintImmediately null graphics
    any idea how to track this null graphics?
    Thanks in advance
    Viru

    My opinion is that either you the images in an array and the thread assigns
    an invalid value for the index of the array.
    Or you have a graphics context without any graphics while the thread attempts
    to display it.
    Or both. (one because of the other)
    Try putting System.out.println() statements in the run method of the thread and
    see if it is doing what it is supposed to be doing.
    In the paint() method try putting the same to see if your graphic contexts are valid.
    Is it an applet or an application ?

  • Null Graphics

    why am I unable to get the graphic of the frame or panel? I have an ImageIcon that I want to draw as background of the panel (or frame..) but if i do something like :
    JFrame.setDefaultLookAndFeelDecorated(true);
                   //Create and set up the window.
                   JFrame frame = new JFrame("Capture");
                   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                   JPanel panel = new JPanel();
                   frame.getContentPane().add(panel, BorderLayout.CENTER);then when I try to get the getGraphics() of the panel or the frame, I get a null pointer..
    how can I draw it?

    you are SOOOOOO RIGHT !
    thanxBut is normally wrong to get the Graphics object this way. One normally overrides paintComponent(Graphics g) and draws everything in this method.

  • Null Graphics objects

    Hello, I am attempting to write a java program that places a graph within a panel that the user can interact with. I have chosen Canvas() as the method to acieve this, but am running into problems with the instantiation of the graphics object- it keeps returning null, and I haven't the faitest idea why. Here is my code in question:
    Canvas canvas = new Canvas();
    Graphics g = canvas.getGraphics();
    'g' is null- when I try to call g.drawLine(), it gives me a nullPointerException. Any help or information about why this is occuring would be greatly appreciated.

    Well, I figured out that I needed to add the canvas to the contentPane before it had a Graphics object associated with it. But now, where the canvas is, there is a just a gray box. SetColor doesn't work, drawLine doesn't work, nothing. Here is the code:
    Canvas canvas = new Canvas();
    contentPane.add(canvas, BorderLayout.WEST);
    show();
    Graphics g = canvas.getGraphics();
    Color white = new Color (255,255,255);
    g.setColor(white);
    setSize(300,200);
    //Sets up the graph lines and tic marks
    int size = 100;
    g.drawLine(0, 0, size, 0);
    g.drawLine(0, 0, 0, size);
    //Horizontal tics
    g.drawLine((size/4), 0, (size/4), (size/10));
    g.drawLine((size/2), 0, (size/2), (size/10));
    g.drawLine(((3*size)/4), 0, ((3*size)/4), (size/10));
    g.drawLine(size, 0, size, (size/10));
    //Vertical tics
    g.drawLine(0, (size/4), (size/10), (size/4));
    g.drawLine(0, (size/2), (size/10), (size/2));
    g.drawLine(0, ((3*size)/4), (size/10), ((3*size)/4));
    g.drawLine(0, size, (size/10), size);
    show();
    As I said, it compiles and runs fine, but there are no lines set up. I even added a bunch of show() statements as a desperate effort to get something to show up. Can anyone help? Thanks
    I hate programming.

  • 7$ question?

    Hi all,
    do you have any idea about the following exception?.
    What i am doing is just i'm calling the SwingUtilities.updateComponentTreeUI(menuBar);
    here menuBar - JMenuBar
    If any of you know the answer kindly reply to this post.
    Thanks.
    java.lang.Exception: Stack trace
    at java.lang.Thread.dumpStack(Unknown Source)
    at javax.swing.SwingGraphics.createSwingGraphics(Unknown
    Source)
    at javax.swing.JComponent._paintImmediately(Unknown
    Source)
    at javax.swing.JComponent.paintImmediately(Unknown Source)
    at javax.swing.RepaintManager.paintDirtyRegions(Unknown
    Source)
    at
    javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown
    Source)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at
    java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown
    Source)
    at
    java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown
    ource)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    java.lang.NullPointerException
    at javax.swing.JComponent._paintImmediately(Unknown
    Source)
    at javax.swing.JComponent.paintImmediately(Unknown Source)
    at javax.swing.RepaintManager.paintDirtyRegions(Unknown
    Source)
    at
    javax.swing.SystemEventQueueUtilities$ComponentWorkRequest.run(Unknown
    Source)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at
    java.awt.EventDispatchThread.pumpOneEventForHierarchy(Unknown
    Source)
    at
    java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown
    Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    In paintImmediately null graphics
    Exception running task: java.lang.NullPointerException
    java.lang.NullPointerException
    at javax.swing.BoxLayout.checkRequests(Unknown Source)
    at javax.swing.BoxLayout.layoutContainer(Unknown Source)
    at java.awt.Container.layout(Unknown Source)
    at java.awt.Container.doLayout(Unknown Source)
    at java.awt.Container.validateTree(Unknown Source)
    at java.awt.Container.validate(Unknown Source)
    at
    javax.swing.SwingUtilities.updateComponentTreeUI(Unknown)

    Hello,
    Please give the section of the code that you think is generating the exception. In your exception, you have encountered quite a few NullPointerException at different regions of the stack trace and I also saw "In paintImmediately null graphics". Are all the graphic elements visible at the time of re-drawing? i.e. are there any elements that you have put that are not visible?
    Ironluca

  • How to make a Graphics2D object from a Graphics object?

    Hallo !
    Graphics g = pj.getGraphics();
    Graphics2D g2 = (Graphics2D) g;I get an Exception as follows:
    java.lang.ClassCastException: sun.awt.windows.WPrintGraphicsWrapper
    Is there an other possibility to to make a Graphics2D Object ? Or can I repair the error on an other way?
    Thank you Wolfgang

    Yes JBuilder makes a reference to this line.
    pj is a PrintJob.
    The only lines in this method for test are
    PrintJob pj = Toolkit.getDefaultToolkit().getPrintJob(p,"PrintWindow",null);
    Graphics g = pj.getGraphics();
    Graphics2D g2 = (Graphics2D) g;
    pj.end();Exception occurred during event dispatching:
    java.lang.ClassCastException: sun.awt.windows.WPrintGraphicsWrapper
    Wolfgang

  • Graphics.drawLine and Graphics.drawRect do not match

    Using a Graphics.scale (not == 1.0, but the value is insignificant) often Graphics.drawLine and Graphics.drawRect do not match (with same and x and y-Values), there are differences of one pixel in x- and y-direction when you use JDK 1.6_Update12 and later in about every third rectangle. The values in the code sample are not significant for getting the problem.
    I am using Windows XP and can get the error with JDK 1.6 Update 12 until JDK 1.6 Update 16, but not with the earlier updates.
    Could this be considered an Java error ?
    public class LbCanvas extends Canvas
       Image scratchPad = null;
       Graphics scratchPadGraphics;
       double small = 0.99;
       public LbCanvas()
          setSize (new Dimension (1354, 1397));
       public void update(Graphics g)
          if (scratchPad==null)
             scratchPad = createImage (this.getSize().width, this.getSize().height);
          scratchPadGraphics = scratchPad.getGraphics();
          paint(scratchPadGraphics);
          g.drawImage (scratchPad, 0, 0, null);
       public void paint(Graphics g)
          super.paint(g);
          ((Graphics2D)g).scale (small, small);
          g.setColor(Color.black);
          for (int i=30; i<900; i+=31)
             g.drawRect (10, i, 150, 21);
             g.drawLine (10, i, 160, i);
    }Edited by: Mausboesie on Oct 1, 2009 2:25 AM

    I tried your code with various scalings--it seems some are better than others. It looks, without checking the implementation, that the problem is in how each andles the scaling and I would definetly consider this a "Java Error".

  • Clock applet example. createImage returns null

    Hello, I'm quite new with AWT and I need help. I cannot use swing.
    I'm trying to make a "normal" app with the applet of the analog clock that is included as an example in the JDK. I have been reading the API of java.awt.applet and I have made the following things:
    1.- I have deleted the Parser classes that are there fore taking the parameters that were used in the html.
    2.- I have made an class that extends Panel and implement Runnable, as same as the class Applet. This class, called XClock, includes an adapted AnalogClock that is the class included in the example.
    I think I have to do the double-buffering. So I have included the following code:
    // Create the offImage for double-buffering.
    offImage = createImage(size.width, size.height);
    offG = offImage.getGraphics();
    Of course, size has the right values. My code compiles ok, but when I run it says that offImage becomes null, so in the second line it throws a NullPointerException.
    I have made the following class to test the XClock class:
    public class Prueba {
    public static void main(String[]args){
    XClock reloj=new XClock();
    XClock extends Panel. �Any help?. Please, it's quite important for me.

    This will make you go:
    import java.awt.event.*;
    import java.awt.*;
    public class Prueba  extends Frame 
         Xclock clock = new Xclock();
    public Prueba ()
         addWindowListener(new WindowAdapter()
        {     public void windowClosing(WindowEvent ev)
              {     setVisible(false);
         setBounds(10,10,400,300);
         add(clock);
         setVisible(true);
    public class Xclock extends Panel
         Image    offImage = null;
         Graphics offG;
    public Xclock()
    public void paint(Graphics g)
         if (offImage == null)
              offImage = createImage(getWidth(),getHeight());
              offG     = offImage.getGraphics();
              offG.drawOval(10,10,250,250);
         g.drawImage(offImage,0,0,this);
    public void update(Graphics g)
         paint(g);
    public static void main(String[] args )
         new Prueba ();
    Noah
    import java.awt.event.*;
    import java.awt.*;
    public class Prueba extends Frame
         Xclock clock = new Xclock();
    public Prueba ()
         addWindowListener(new WindowAdapter()
    {     public void windowClosing(WindowEvent ev)
              {     setVisible(false);
         setBounds(10,10,400,300);
         add(clock);
         setVisible(true);
    public class Xclock extends Panel
         Image offImage = null;
         Graphics offG;
    public Xclock()
    public void paint(Graphics g)
         if (offImage == null)
              offImage = createImage(getWidth(),getHeight());
              offG = offImage.getGraphics();
              offG.drawOval(10,10,250,250);
         g.drawImage(offImage,0,0,this);
    public void update(Graphics g)
         paint(g);
    public static void main(String[] args )
         new Prueba ();
    }

  • Graphics error

    I am trying to draw a photograph in a JFrame with some other information. I set up and load the Image and draw it to a buffered image. When I go and get the graphics from the panel I want to draw to, I get null back. My code look like:
    backbuffer = new BufferedImage(photoPanel.getWidth(), photoPanel.getHeight(), BufferedImage.TYPE_INT_RGB);
            g2 = backbuffer.createGraphics();
            try {
                photo = tk.getImage(photopath);
            } catch (Exception e) {
                photo = tk.getImage("images/null.png");
            g2.drawImage(photo, 0, 0, photoPanel.getWidth(), photoPanel.getHeight(), null);
            if (photoPanel.getGraphics() == null) {
                System.out.println("Null Graphics");
            } else {
                photoPanel.getGraphics().drawImage(backbuffer,640,20,200,200,this);
            }Both the JPanel (photoPanel) and JFrame return nothing. This is the first time I have run into a problem like this. The class file I am writing extends JFrame and the JPanel is a local variable.
    I am using Java 1.6 and Net Beans 5.5

    If the gui is not realized then none of the components such as JFrame and JPanel will have a
    non&#8211;null graphics context. Using getGraphics is a con anyway. Use a JPanel and
    override paintComponent for proper drawing.
    import java.awt.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    public class FrameExtension extends JFrame {
        BufferedImage backbuffer;
        BufferedImage photo;
        public FrameExtension() {
            loadImage();
            getContentPane().add(photoPanel);
            setSize(400,400);
            System.out.println("graphics context before realization = " +
                                photoPanel.getGraphics());
            setVisible(true);
            System.out.println("graphics context after realization  = " +
                                photoPanel.getGraphics());
        private void loadImage() {
            String photopath = "images/cougar.jpg";
            boolean groping = true;
            while(groping) {
                try {
                    photo = ImageIO.read(new File(photopath));
                    groping = false;
                } catch (Exception e) {
                    System.out.println("Load error: " + e.getClass().getName() +
                                       "  " + e.getMessage());
                    if(photopath.equals("images/null.png"))
                        groping = false;
                    photopath = "images/null.png";
        JPanel photoPanel = new JPanel() {
            protected void paintComponent(Graphics g) {
                if(backbuffer == null) {
                    backbuffer = new BufferedImage(getWidth(), getHeight(),
                                                   BufferedImage.TYPE_INT_RGB);
                    Graphics2D g2 = backbuffer.createGraphics();
                    g2.setBackground(getBackground());
                    g2.clearRect(0, 0, getWidth(), getHeight());
                    g2.drawImage(photo, 0, 0, null);
                    g2.dispose();
                g.drawImage(backbuffer,0,0,this);
        public static void main(String[] args) {
            new FrameExtension();
    }

  • Merge original image and drawn graphic together as an new image

    Hi,
    I created an application which can draw graphic(line, rectangle, etc) upon an displayed image. However, I want the application be able to merge the drawn graphic into the image and then save it as a new image. Does anyone know how to do that? I am using Java 2D in my application.
    Thanks for help.

    Hi,
    Hope this is the code that you are looking for
    *     @ PlayWithImage.java
    *     @ Author : Sathish Rao S
    *     @ Date : 14th March 2002
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.awt.Frame;
    import java.awt.Image;
    import java.awt.Color;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.Composite;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.geom.Rectangle2D;
    import java.awt.image.BufferedImage;
    import java.awt.font.FontRenderContext;
    import com.sun.image.codec.jpeg.JPEGCodec;
    import com.sun.image.codec.jpeg.JPEGEncodeParam;
    import com.sun.image.codec.jpeg.JPEGImageDecoder;
    import com.sun.image.codec.jpeg.JPEGImageEncoder;
    public class PlayWithImage {
         public static void main(String args[]) {
              EditImage ei = new EditImage();
              ei.drawImage();
              System.exit(0);
    class EditImage {
         File tmpf;
         FileOutputStream fout;
         Frame frame=null;
         Graphics g=null;
         String filePath = "D:\\Your\\Folder\\Here";
         public void drawImage() {
              try
                   frame=new Frame();
                   frame.addNotify();
                   //new image's width and height
                   int width = 117;
                   int height = 57;
                   BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
                   g=image.getGraphics();
                   Graphics2D g2=(Graphics2D)g;
                   g2.setPaint(new Color(255,255,255));
                   Rectangle2D background = new Rectangle2D.Double(0,0,width,height);
                   g2.fill(background);
                   RenderingHints hints=new RenderingHints(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
                   g2.setRenderingHints(hints);
                   try
                        File f = new File("your_image.jpg");
                        FileInputStream fis = new FileInputStream(f.getAbsolutePath());
                        JPEGImageDecoder JPEG_decoder = JPEGCodec.createJPEGDecoder(fis);
                        BufferedImage buffimg = JPEG_decoder.decodeAsBufferedImage();
                        g2.drawImage(buffimg, 0, 0, null);
                        g2.setColor(new Color(80,80,255));
                        g2.setFont(new Font("Times New Roman",Font.BOLD,12));
                        paintCenteredText(g2,"Your_Name_here",(width+40)/2,54);
                   }catch(Exception e)
                        System.out.println(e);
                    *     Add your part of graphics here
                   g2.setPaint(new Color(0,0,0));
                   Rectangle2D border = new Rectangle2D.Double(0,0,width-1,height-1);
                   g2.draw(border);
                   //     This will create a new temp file.
                   //     Your Original file is not disturbed :)
                   tmpf=File.createTempFile("your_new_image",".jpg",new File(filePath));
                   fout=new FileOutputStream(tmpf);
                   JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(fout);
                   JPEGEncodeParam  param =  encoder.getDefaultJPEGEncodeParam(image);
                   encoder.setJPEGEncodeParam(param);
                   encoder.encode(image);
                   fout.close();
              }catch(Exception e)
                   System.out.println("Exception here");
              }finally
                   /*Clean up all the resources*/
                   if(g!=null)g.dispose();
                   if(frame!=null)frame.removeNotify();
         protected void paintCenteredText(Graphics2D g2, String s, int centerx,int baselineY)
              FontRenderContext frc=g2.getFontRenderContext();
              Rectangle2D bounds=g2.getFont().getStringBounds(s,frc);
              float wdth=(float)bounds.getWidth();
              g2.drawString(s,centerx - wdth/2,baselineY);

  • Graphics g!!

    I want to declare Graphics g=??. Any help?

    Here are some possibilities:Graphics g;
    Graphics g= null;
    Graphics g= this.getGraphics();
    Graphics g= new BufferedImage(300,200,BufferedImage.TYPE_INT_ARGB ).getGraphics();
    Graphics g = new Graphics() {
      * Write implementations for the abstract methods here
    };

  • Virtual Universe and Graphics Configuration

    Hi,
    I have a virtual universe and create a Canvas3D Object with a 'null' Graphics Configuration. How do I get a valid Graphics Configuration to pass to the constructor in Canvas3D?
    Thanks,
    Molly.

    I've never had any problem using "null" Graphics Configuration parameter.
    But it is better to set it to SimpleUniverse.getPreferredConfiguration() , especially for big projects : when you compile with null parameter in JBuilder8 it says that in a warning. If you choose to use the parameter SimpleUniverse.getPreferredConfiguration() you need to import com.sun.j3d.utils.universe.SimpleUniverse;
    @+

  • Programming a Pencil Tool on Paint?

    Here's my code for Scribble(a pencil tool) and its superclass Shape. Basically, my program remembers where the mouse has been and draws a line from the previous point to the current point. However, the scribble doesn't show up (occasionally you will see a small line at the very end) I think the problem is that each Scribble object only has one previous and one current. Therefore, there is only 1 line left at the end. How can I correct this?
    Thanks in advance!
    Note: this doesn't run since there are about 5 other classes needed. I guess can post them if you want? xD
    import java.awt.*;
    public class Scribble extends Shape{
         protected Point startpt, endpt;
         protected Point previous, current;
         int count = 0;
        public Scribble(Point start, DrawingCanvas dcanvas){
         super();
         System.out.println("SCRIBBLE CREATED!!!!!!!\n\n");
         startpt = start;
         current = start;
         endpt = start;
         canvas = dcanvas;
         bounds = new Rectangle(start);
        public void resize(Point anchor, Point end){
         super.resize(anchor, end);
         previous = current;
         startpt = anchor;
         current = end;
         endpt = end;
        public void translate(int dx, int dy){
         super.translate(dx, dy);
         previous.translate(dx, dy);
         current.translate(dx, dy);
         startpt.translate(dx, dy);
         endpt.translate(dx, dy);
        public void draw(Graphics g, Rectangle regionToDraw){
              count++;
              System.out.println(count);
         if (!bounds.intersects(regionToDraw)){
             return;
         g.setColor(super.getColor());
         g.drawLine((int)previous.getX(), (int)previous.getY(), (int)current.getX(), (int)current.getY());
         if (isSelected) { // if selected, draw the resizing knobs
                           // along the 4 corners
             Rectangle[] knobs = getKnobRects();
             for (int i = 0; i < knobs.length; i++)
              g.fillRect(knobs.x, knobs[i].y,
                   knobs[i].width, knobs[i].height);
    protected Rectangle[] getKnobRects(){
         Rectangle[] knobs = new Rectangle[2];
         knobs[0] = new Rectangle((int)startpt.getX() - KNOB_SIZE/2,
                        (int)startpt.getY() - KNOB_SIZE/2, KNOB_SIZE, KNOB_SIZE);
         knobs[1] = new Rectangle((int)endpt.getX() - KNOB_SIZE/2,
                        (int)endpt.getY()- KNOB_SIZE/2, KNOB_SIZE, KNOB_SIZE);
         return knobs;
    protected int getKnobContainingPoint(Point pt){
         if (!isSelected) return NONE;
         Rectangle[] knobs = getKnobRects();
         for (int i = 0; i < knobs.length; i++)
         if (knobs[i].contains(pt))
              return i;
         return NONE;
    }import java.awt.*;
    import java.util.*;
    import java.io.*;
    public abstract class Shape implements Serializable, Cloneable{
         private Color color;
    protected Rectangle bounds;
    protected boolean isSelected;
    public DrawingCanvas canvas;
    protected static final int KNOB_SIZE = 6;
    protected static final int NONE = -1;
    protected static final int NW = 0;
    protected static final int SW = 1;
    protected static final int SE = 2;
    protected static final int NE = 3;
         Shape(){
              color = Color.darkGray;
         public Color getColor(){
         return color;
         public Object clone(){
              try{
              Shape copy = (Shape)super.clone();
              copy.setBounds(bounds);
              return copy;
              catch(CloneNotSupportedException c){
                   return null;
         public void setColor(Color newColor){
         color = newColor;
         canvas.repaint();
         /** The "primitive" for all resizing/moving/creating operations that
         * affect the rect bounding box. The current implementation just resets
         * the bounds variable and triggers a re-draw of the union of the old &
         * new rectangles. This will redraw the shape in new size and place and
         * also "erase" if bounds are now smaller than before.
         protected void setBounds(Rectangle newBounds){
              Rectangle oldBounds = bounds;
              bounds = newBounds;
              updateCanvas(oldBounds.union(bounds));
         /** The resize operation is called when first creating a rect, as well as
         * when later resizing by dragging one of its knobs. The two parameters
         * are the points that define the new bounding box. The anchor point
         * is the location of the mouse-down event during a creation operation
         * or the opposite corner of the knob being dragged during a resize
         * operation. The end is the current location of the mouse.
         public void resize(Point anchor, Point end){
              Rectangle newRect = new Rectangle(anchor);
              // creates smallest rectange which
              // includes both anchor & end
              newRect.add(end);
              // reset bounds & redraw affected areas
              setBounds(newRect);
              canvas.repaint();
         /** The translate operation is called when moving a shape by dragging in
         * the canvas. The two parameters are the delta-x and delta-y to move
         * by. Note that either or both can be negative. Create a new rectangle
         * from our bounds and translate and then go through the setBounds()
         * primitive to change it.
         public void translate(int dx, int dy){
              Rectangle newRect = new Rectangle(bounds);
              newRect.translate(dx, dy);
              setBounds(newRect);
              canvas.repaint();
         /** Used to change the selected state of the shape which will require
         * updating the affected area of the canvas to add/remove knobs.
         public void setSelected(boolean newState){
              isSelected = newState;
              // need to erase/add knobs
              // including extent of extended bounds
              updateCanvas(bounds, true);
              canvas.repaint();
         /** The updateCanvas() methods are used when the state has changed
         * in such a way that it needs to be refreshed in the canvas to properly
         * reflect the new settings. The shape should take responsibility for
         * messaging the canvas to properly update itself. The appropriate AWT/JFC
         * way to re-draw a component is to send it the repaint() method with the
         * rectangle that needs refreshing. This will cause an update() event to
         * be sent to the component which in turn will call paint(), where the
         * real drawing implementation goes. See the paint() method in
         * DrawingCanvas to see how it is implemented.
         protected void updateCanvas(Rectangle areaOfChange, boolean enlargeForKnobs){
                   System.out.println("canvas2 updated");
              Rectangle toRedraw = new Rectangle(areaOfChange);
              if (enlargeForKnobs)
              toRedraw.grow(KNOB_SIZE/2, KNOB_SIZE/2);
              canvas.repaint(toRedraw);
         protected void updateCanvas(Rectangle areaOfChange){
                   System.out.println("canvas updated");
              updateCanvas(areaOfChange, isSelected);
              public Rectangle getBounds(){
                   return bounds;
         /** When the DrawingCanvas needs to determine which shape is under
         * the mouse, it asks the shape to determine if a point is "inside".
         * This method should returns true if the given point is inside the
         * region for this shape. For a rectangle, any point within the
         * bounding box is inside the shape.
         public boolean inside(Point pt){
              return bounds.contains(pt);
         /** When needed, we create the array of knob rectangles on demand. This
         * does mean we create and discard the array and rectangles repeatedly.
         * These are small objects, so perhaps it is not a big deal, but
         * a valid alternative would be to store the array of knobs as an
         * instance variable of the Shape and and update the knobs as the bounds
         * change. This means a little more memory overhead for each Shape
         * (since it is always storing the knobs, even when not being used) and
         * having that redundant data opens up the possibility of bugs from
         * getting out of synch (bounds move but knobs didn't, etc.) but you may
         * find that a more appealing way to go. Either way is fine with us.
         * Note this method provides a nice unified place for one override from
         * a shape subclass to substitute fewer or different knobs.
         protected Rectangle[] getKnobRects(){
                   System.out.println("knobs gotten");
              Rectangle[] knobs = new Rectangle[4];
              knobs[NW] = new Rectangle(bounds.x - KNOB_SIZE/2,
                             bounds.y - KNOB_SIZE/2, KNOB_SIZE, KNOB_SIZE);
              knobs[SW] = new Rectangle(bounds.x - KNOB_SIZE/2,
                             bounds.y + bounds.height - KNOB_SIZE/2,
                             KNOB_SIZE, KNOB_SIZE);
              knobs[SE] = new Rectangle(bounds.x + bounds.width - KNOB_SIZE/2,
                             bounds.y + bounds.height - KNOB_SIZE/2,
                             KNOB_SIZE, KNOB_SIZE);
              knobs[NE] = new Rectangle(bounds.x + bounds.width - KNOB_SIZE/2,
                             bounds.y - KNOB_SIZE/2,
                             KNOB_SIZE, KNOB_SIZE);
              return knobs;
         /** Helper method to determine if a point is within one of the resize
         * corner knobs. If not selected, we have no resize knobs, so it can't
         * have been a click on one. Otherwise, we calculate the knob rects and
         * then check whether the point falls in one of them. The return value
         * is one of NW, NE, SW, SE constants depending on which knob is found,
         * or NONE if the click doesn't fall within any knob.
         protected int getKnobContainingPoint(Point pt){
                   System.out.println("resize knobs");
              // if we aren't selected, the knobs
              // aren't showing and thus there are no knobs to check
              if (!isSelected) return NONE;
              Rectangle[] knobs = getKnobRects();
              for (int i = 0; i < knobs.length; i++)
              if (knobs[i].contains(pt))
                   return i;
              return NONE;
         /** Method used by DrawingCanvas to determine if a mouse click is starting
         * a resize event. In order for it to be a resize, the click must have
         * been within one of the knob rects (checked by the helper method
         * getKnobContainingPoint) and if so, we return the "anchor" ie the knob
         * opposite this corner that will remain fixed as the user drags the
         * resizing knob of the other corner around. During the drag actions of a
         * resize, that fixed anchor point and the current mouse point will be
         * passed to the resize method, which will reset the bounds in response
         * to the movement. If the mouseLocation wasn't a click in a knob and
         * thus not the beginning of a resize event, null is returned.
    public Point getAnchorForResize(Point mouseLocation){
              System.out.println("is it a resize?");
    int whichKnob = getKnobContainingPoint(mouseLocation);
    if (whichKnob == NONE) // no resize knob is at this location
    return null;
    Rectangle[] knobs = getKnobRects();
    whichKnob = Math.abs(whichKnob - (int)(knobs.length / 2));
    return (new Point(knobs[whichKnob].x + knobs[whichKnob].width /2,
    knobs[whichKnob].y + knobs[whichKnob].height/2));
    public abstract void draw(Graphics g, Rectangle regionToDraw);

    line left at the end. How can I correct this?java.awt.Polygon (or Polygon2D)
    Here are a few of my thoughts
    #1 There is a Shape interface in core java already, as well as plenty of very useful shapes (Rectangle, Ellipse2D, Area). Shape has some really nice features like contains(...) and intersects(...). By creating a separate class for your Shape objects, you ensure that the two will be incompatible.
    #2 As tempting as it is, it is a bad idea to include a Color with a shape. What if you want it to have more than one Color? What if you want the insides of the shape to be filled by an Image? I just created and posted a class on the java forums called Renderable, which combines a java.awt.Shape with a java.awt.Paint.
    #3 Below is my PaintArea class. It "scribbles" on an Image. Maybe this will give you some ideas. To compile it, you will either have to find my MathUtils class (which I've posted here before) or reimplement the distance and angle methods. There is also a reference to WIndowUtilities... find that or remove it and put the PaintArea in a Frame and do setVisible(true)
    You are welcome to use and modify this code, but please don't change the package and please make sure that you add attribution if you submit this in an academic setting.
    * Created on Jun 15, 2005 by @author Tom Jacobs
    package tjacobs.ui.ex;
    import java.awt.image.BufferedImage;
    import java.awt.*;
    import java.awt.event.*;
    import java.beans.PropertyChangeEvent;
    import java.beans.PropertyChangeListener;
    import javax.swing.ImageIcon;
    import javax.swing.JComboBox;
    import javax.swing.JComponent;
    import javax.swing.JPanel;
    import javax.swing.JToolBar;
    import tjacobs.MathUtils;
    import tjacobs.ui.util.WindowUtilities;
    * PaintArea is a component that you can draw in similar to but
    * much simpler than the windows paint program.
    public class PaintArea extends JComponent {
         private static final long serialVersionUID = 0;
         BufferedImage mImg; //= new BufferedImage();
         int mBrushSize = 1;
         private boolean mSizeChanged = false;
         private Color mColor1, mColor2;
         static class PaintIcon extends ImageIcon {
              public static final long serialVersionUID = 0;
              int mSize;
              public PaintIcon(Image im, int size) {
                   super(im);
                   mSize = size;
         public PaintArea() {
              super();
              setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
              addComponentListener(new CListener());
              MListener ml = new MListener();
              addMouseListener(ml);
              addMouseMotionListener(ml);
              setBackground(Color.WHITE);
              setForeground(Color.BLACK);
         public void paintComponent(Graphics g) {
              if (mSizeChanged) {
                   handleResize();
              //g.drawImage(mImg, mImg.getWidth(), mImg.getHeight(), null);
              g.drawImage(mImg, 0, 0, null);
              //super.paintComponent(g);
              //System.out.println("Image = " + mImg);
              //System.out.println("Size: " + mImg.getWidth() + "," + mImg.getHeight());
         public void setBackground(Color c) {
              super.setBackground(c);
              if (mImg != null) {
                   Graphics g = mImg.getGraphics();
                   g.setColor(c);
                   g.fillRect(0, 0, mImg.getWidth(), mImg.getHeight());
                   g.dispose();
         public void setColor1(Color c) {
              mColor1 = c;
         public void setColor2(Color c) {
              mColor2 = c;
         public Color getColor1() {
              return mColor1;
         public Color getColor2() {
              return mColor2;
         class ToolBar extends JToolBar {
              private static final long serialVersionUID = 1L;
              ToolBar() {
                   final ColorButton fore = new ColorButton();
                   fore.setToolTipText("Foreground Color");
                   final ColorButton back = new ColorButton();
                   back.setToolTipText("Background Color");
                   JComboBox brushSize = new JComboBox();
                   //super.createImage(1, 1).;
                   FontMetrics fm = new FontMetrics(getFont()) {
                        private static final long serialVersionUID = 1L;};
                   //int ht = fm.getHeight();
                   int useheight = fm.getHeight() % 2 == 0 ? fm.getHeight() + 1 : fm.getHeight();
                   final BufferedImage im1 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   Graphics g = im1.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2, useheight / 2, 1, 1);
                   g.dispose();
                   //im1.setRGB(useheight / 2 + 1, useheight / 2 + 1, 0xFFFFFF);
                   final BufferedImage im2 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   g = im2.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2 - 1, useheight / 2 - 1, 3, 3);
                   g.dispose();
    //               im2.setRGB(useheight / 2 - 1, useheight / 2 - 1, 3, 3, new int[] {     0, 0xFFFFFF, 0,
    //                                                            0xFFFFFF, 0xFFFFFFF, 0xFFFFFF,
    //                                                            0, 0xFFFFFF, 0}, 0, 1);
                   final BufferedImage im3 = new BufferedImage(useheight, useheight, BufferedImage.TYPE_INT_RGB);
                   g = im3.getGraphics();
                   g.setColor(Color.WHITE);
                   g.fillRect(0, 0, useheight, useheight);
                   g.setColor(Color.BLACK);
                   g.fillOval(useheight / 2 - 2, useheight / 2 - 2, 5, 5);
                   g.dispose();
    //               im3.setRGB(useheight / 2 - 2, useheight / 2 - 2, 5, 5, new int[] {     0, 0, 0xFFFFFF, 0, 0, 
    //                                                            0, 0xFFFFFF, 0xFFFFFFF, 0xFFFFFF, 0,
    //                                                            0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF, 0xFFFFFF,
    //                                                            0, 0xFFFFFF, 0xFFFFFFF, 0xFFFFFF, 0,
    //                                                            0, 0, 0xFFFFFF, 0, 0}, 0, 1);
                   //JLabel l1 = new JLabel("1 pt", new ImageIcon(im1), JLabel.LEFT);
                   //JLabel l2 = new JLabel("3 pt", new ImageIcon(im2), JLabel.LEFT);
                   //JLabel l3 = new JLabel("5 pt", new ImageIcon(im3), JLabel.LEFT);
                   brushSize.addItem(new PaintIcon(im1, 1));
                   brushSize.addItem(new PaintIcon(im2, 3));
                   brushSize.addItem(new PaintIcon(im3, 5));
                   //brushSize.addItem("Other");
                   add(fore);
                   add(back);
                   add(brushSize);
                   PropertyChangeListener pl = new PropertyChangeListener() {
                        public void propertyChange(PropertyChangeEvent ev) {
                             Object src = ev.getSource();
                             if (src != fore && src != back) {
                                  return;
                             Color c = (Color) ev.getNewValue();
                             if (ev.getSource() == fore) {
                                  mColor1 = c;
                             else {
                                  mColor2 = c;
                   fore.addPropertyChangeListener("Color", pl);
                   back.addPropertyChangeListener("Color", pl);
                   fore.changeColor(Color.BLACK);
                   back.changeColor(Color.WHITE);
                   brushSize.addItemListener(new ItemListener() {
                        public void itemStateChanged(ItemEvent ev) {
                             System.out.println("ItemEvent");
                             if (ev.getID() == ItemEvent.DESELECTED) {
                                  return;
                             System.out.println("Selected");
                             Object o = ev.getItem();
                             mBrushSize = ((PaintIcon) o).mSize;
                   //Graphics g = im1.getGraphics();
                   //g.fillOval(0, 0, 1, 1);
                   //BufferedImage im1 = new BufferedImage();
                   //BufferedImage im1 = new BufferedImage();
         protected class MListener extends MouseAdapter implements MouseMotionListener {
              Point mLastPoint;
              public void mouseDragged(MouseEvent me) {
                   Graphics g = mImg.getGraphics();
                   if ((me.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
                        g.setColor(mColor1);
                   } else {
                        g.setColor(mColor2);
                   Point p = me.getPoint();
                   if (mLastPoint == null) {
                        g.fillOval(p.x - mBrushSize / 2, p.y - mBrushSize / 2, mBrushSize, mBrushSize);
                        //g.drawLine(p.x, p.y, p.x, p.y);
                   else {
                        g.drawLine(mLastPoint.x, mLastPoint.y, p.x, p.y);
                        //g.fillOval(p.x - mBrushSize / 2, p.y - mBrushSize / 2, mBrushSize, mBrushSize);
                        double angle = MathUtils.angle(mLastPoint, p);
                        if (angle < 0) {
                             angle += 2 * Math.PI;
                        @SuppressWarnings("unused")
                        double distance = MathUtils.distance(mLastPoint, p) * 1.5;
                        if (angle < Math.PI / 4 || angle > 7 * Math.PI / 4 || Math.abs(Math.PI - angle) < Math.PI / 4) {
                             for (int i = 0; i < mBrushSize / 2; i ++) {
                                  g.drawLine(mLastPoint.x, mLastPoint.y + i, p.x, p.y + i);
                                  g.drawLine(mLastPoint.x, mLastPoint.y - i, p.x, p.y - i);
    //                              System.out.println("y");
    //                              System.out.println("angle = " + angle / Math.PI * 180);
                        else {
                             for (int i = 0; i < mBrushSize / 2; i ++) {
                                  g.drawLine(mLastPoint.x + i, mLastPoint.y, p.x + i, p.y);
                                  g.drawLine(mLastPoint.x  - i, mLastPoint.y, p.x - i, p.y);
    //                              System.out.println("x");
    //                    System.out.println("new = " + PaintUtils.printPoint(p));
    //                    System.out.println("last = " + PaintUtils.printPoint(mLastPoint));
                        //System.out.println("distance = " + distance);
                        //Graphics2D g2 = (Graphics2D) g;
                        //g2.translate(mLastPoint.x + mBrushSize / 2, mLastPoint.y);
                        //g2.rotate(angle);
                        //g2.fillRect(0, 0, (int) Math.ceil(distance), mBrushSize);
                        //g2.rotate(-angle);
                        //g2.translate(-mLastPoint.x + mBrushSize / 2, -mLastPoint.y);
    //                    g.setColor(Color.RED);
    //                    g.drawRect(p.x, p.y, 1, 1);
                   mLastPoint = p;
                   g.dispose();
                   repaint();
              public void mouseMoved(MouseEvent me) {}
              public void mouseReleased(MouseEvent me) {
                   mLastPoint = null;
         private void handleResize() {
              Dimension size = getSize();
              mSizeChanged = false;
              if (mImg == null) {
                   mImg = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB);
                   Graphics g = mImg.getGraphics();
                   g.setColor(getBackground());
                   g.fillRect(0, 0, mImg.getWidth(), mImg.getHeight());
                   g.dispose();
              else {
                   int newWidth = Math.max(mImg.getWidth(),getWidth());
                   int newHeight = Math.max(mImg.getHeight(),getHeight());
                   if (newHeight == mImg.getHeight() && newWidth == mImg.getWidth()) {
                        return;
                   BufferedImage bi2 = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
                   Graphics g = bi2.getGraphics();
                   g.setColor(getBackground());
                   g.fillRect(0, 0, bi2.getWidth(), bi2.getHeight());
                   g.drawImage(mImg, mImg.getWidth(), mImg.getHeight(), null);
                   g.dispose();
                   mImg = bi2;
         public JToolBar getToolBar() {
              if (mToolBar == null) {
                   mToolBar = new ToolBar();
              return mToolBar;
         private ToolBar mToolBar;
         public static void main (String args[]) {
              PaintArea pa = new PaintArea();
              JPanel parent = new JPanel();
              parent.setLayout(new BorderLayout());
              parent.add(pa, BorderLayout.CENTER);
              pa.setPreferredSize(new Dimension(150, 150));
              parent.add(pa.getToolBar(), BorderLayout.NORTH);
              WindowUtilities.visualize(parent);
         protected class CListener extends ComponentAdapter {
              public void componentResized(ComponentEvent ce) {
                   mSizeChanged = true;
    }

  • How to print a text file using Java

    How can I print a text file using Java without converting the output to an image format. Is there anyway I can send the characters in the text file as it is for a print job? I did get a listing doing this ... but that converted the text to an image format before printing....
    THanks,.

    Hi I had to write a print api from scratch, and I did not convert the output to image. Go and read up on the following code. I know there is a Tutorial on Sun about the differant sections of the snippet.
    private void printReport()
         Frame tempFrame = new Frame(getName());
         PrintJob printerJob = Toolkit.getDefaultToolkit().getPrintJob(tempFrame, "Liesltext", null);
         Graphics g = printerJob.getGraphics();
                    //I wrote the method below for calculations
         printBasics(g);
         g.dispose();
         printerJob.end();
    }This alone wont print it you have to do all the calculations in the printBasics method. And as I said I wrote this from scratch and all I did was research first the tutorial and the white papers
    Ciao

  • Creating print job without printerDialog() having everytime

    hello guys i got to print without the need of having to see
    the print dialog popup,
    do help me
    with regards
    thank you

    this is my simple code how to print
    PrintJob pj = Toolkit.getDefaultToolkit().getPrintJob (this, "Just Print",null);
    Graphics pg = pj.getGraphics();
    output.printAll(pg);
    pj.end();
    is anyone overhere to tell me how to
    print with out that printerDialog

Maybe you are looking for