Painting multiple graphic objects

Hi, I need to create something where I can paint rectangles and circles etc on a canvas.
Almost like MS Paint.
I guess I must use a JComponent to paint on, but my problem is how does it store all previously painted objects, e.g if i draw 3 rectangles, the minimize and maximize the window (i.e call update()), only the last rectangle is visible.
Must I store everything in an array, and then traverse it everytime update() is called ?
Surely there must be an easier way ?

There is one, it called BufferedImage, you create one then get it graphics, draw on it every time you want (not in the pain method), and in the paint method you draw this bufferedimage to the graphics.
BufferedImage b1;
Graphics g1;
b1 = new BufferedImage(w,h,BufferedImage.TYPE_3BYTE_BGR);
g1 = b1.getGraphics();
g1.setColor(Color.red);
g1.drawRect(100,100,100,100);
public void paintComponent(Graphics g)
super.paintComponent(g);
g.drawImage(b1,0,0,null);
Noah

Similar Messages

  • Multiple graphics objects?

    Is there any way to plot different graphs in multiple Xmath Graphics windows?  I know that the graphics window can be divided into a matrix of subplots, but what I'd like to do is plot two graphs in one window and a third graph in a second window.  I know in MATLAB, you can do subplots as well as plotting multiple figures in different windows.  Does MATRIXx have anything like this?
    Alternatively, is there any way to subdivide the graphics window into two rows and two columns with one plot stretched across both columns of the first row and two smaller graphs taking the spots { row = 2, column = 1 } and { row = 2, column = 2 }?  For the first plot, I tried doing something like { row = 1, column = [ 1, 2 ] }, but the debugger informed me that keyword column only accepts integer values.
    Thanks,
    Luke G.

    Hi Luke,
    Yes, Xmath does support multiple plot windows. You have to use the Plot2D command for multiple windows, using the {win=num} option.
    To plot graphs in subplot areas, use the {posn=[numrows,numcols,row,col,rowspan,colspan]} option. This syntax works in both Plot and Plot2D and does exactly what you want.
    Dirk

  • Attaching MouseListeners to multiple graphics Objects ie rectangles

    Can any one please help me by telling me how I can go about attaching mouselisteners to different rectangles in an application using one panel. I m not looking for code but any thing that my show me the way to this. Its very important that i do this.
    Please help me
    Sq2000

    In the future, Swing related questions should be
    posted in the Swing forum.
    Maybe you just use a JPanel as a rectangle by setting
    the border of the panel. Then you can add a
    MouseListener to the panel.The code is as follows
    import javax.swing.*;
       import java.awt.*;
       import java.awt.geom.*;
       import java.awt.image.*;
       import java.awt.event.MouseEvent;
         import javax.swing.event.MouseInputAdapter;
        class MapImager extends JPanel
               BufferedImage imageMap;
              private static JFrame frame = new JFrame();
               //private String botswana = "Images/botswana.jpg";
               private Rectangle2D.Double square =
               new Rectangle2D.Double(0, 0, 350, 350);
               private GradientPaint gradient =
               new GradientPaint(0, 0, Color.red, 175, 175, Color.yellow,true); // true means to repeat pattern
               private final static int SQUARE_EDGE_LENGTH = 10;
                private static JPanel panel;
                private static int xPos;
                private static int yPos;
                private static int xP;
              private static int yP;
              private MapPanel mapPanel;
               public MapImager (){
                  //imageMap = getBufferedImage(botswana, this);
                   xPos = 186;yPos = 100;
              static MouseInputAdapter mia = new MouseInputAdapter(){
                   public void mousePressed(MouseEvent e){
                        xPos = e.getX();
                       System.out.println(" The X2 When mousePressed Cordinates are "+xPos);
                       yPos = e.getY();
                       System.out.println(" The Y2 When mousePressed Cordinates are "+yPos);
                       frame.repaint();
                   public void mouseDragged(MouseEvent e){
                        xPos = e.getX();
                       System.out.println(" The X2 When mouseDragged Cordinates are "+xPos);
                       yPos = e.getY();
                       System.out.println(" The Y2 When mouseDragged Cordinates are "+yPos);
                       frame.repaint();
               public void paintComponent (Graphics g){
                 Graphics2D g2d = (Graphics2D)g;
                 this.setBackground(Color.WHITE);
                   g2d.setPaint(gradient);
                   g2d.fill(square);
                     g2d.drawImage (imageMap, 0, 0, this);
                   g.setColor(Color.RED);//I want to draw as many as i want and have each move freely on the frame.
                   g.fillRect(xPos-(SQUARE_EDGE_LENGTH/2), yPos-(SQUARE_EDGE_LENGTH/2), SQUARE_EDGE_LENGTH, SQUARE_EDGE_LENGTH);
         public static BufferedImage getBufferedImage(String imageFile,Component c){
             Image image = c.getToolkit().getImage(imageFile);
             waitForImage(image, c);
             BufferedImage bufferedImage =
                new BufferedImage(image.getWidth(c), image.getHeight(c),
                            BufferedImage.TYPE_INT_RGB);
             Graphics2D g2d = bufferedImage.createGraphics();
             g2d.drawImage(image, 0, 0, c);
             return(bufferedImage);
         public static boolean waitForImage(Image image, Component c){
             MediaTracker tracker = new MediaTracker(c);
             tracker.addImage(image, 0);
             try {
                tracker.waitForAll();
                 catch(InterruptedException ie) {}
             return(!tracker.isErrorAny());
           public static void main(String[] args){
                  MapImage map = new MapImage();
                  frame.add(map);
                   frame.addMouseListener(mia);
                   frame.addMouseMotionListener(mia);
                 frame.setSize(360, 380);
                  frame.setTitle("Map of Botswana");
                  frame.setVisible(true);
                  frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
       }Sq2000

  • Graphics object disappears

    Hi,
    My question is - why when I paint a graphics object (a java 2D object) onto a Frame , my graphics object appears on the screen for literally a split second and then disappears.
    How can I prevent this?
    Here's the code:
    public void paintSimple()
    Graphics h = null;
    show();
    h = this.getContentPane().getGraphics() ;
    Polygon p = new Polygon();
    p.addPoint(1,34);
    p.addPoint(23, 344);
    p.addPoint(234, 3);
    p.addPoint(12,42);
    h.setColor(Color.magenta);
    h.drawLine(1,222,333,44);
    this.getContentPane().update(h);
    Thanks,
    rpodolny

    Hi,
    Just a quick idea ...
    Your class possibly extends frame ...
    then overwrite the following:
    public void paint(Graphics g) {
    update(g);
    and ...
    public void update(Graphics g) {
    Graphics2D gd = (Graphics2D) g;
    Polygon p = new Polygon();
    p.addPoint(1,34);
    p.addPoint(23, 344);
    p.addPoint(234, 3);
    p.addPoint(12,42);
    gd.setColor(Color.magenta);
    gd.drawLine(1,222,333,44);
    //probably draw you Polygon somewhere ....
    I hope this is helping a bit. I think that the image is drawn and the over-drawn immediately after in the underlying methods. Now your drawing should be painted in every update so it should stay on the screen ...
    Hope this helps,
    Tim

  • Painting a SVG file to a Graphics object

    I'd like to import a SVG file and paint it's contents on a Graphics object.
    Something like this:
    SVGImage img = new SVGImage( "example.svg" );
    And then, a method like this:
    img.render( Graphics g , int x , int y );
    That's pretty much all I need. Please keep it simple.
    Oh and, if you're going to redirect me to either Batik or SVGSalamander, would you mind telling me a simple way of creating this kind of code with those engines?
    By the way: If possible, I'd also like to rotate the image on the render method, as in:
    render ( Graphics g , int x , int y , int angle )
    But if that turns out to be too complicated, just rendering it is already really good.
    Thank you very much. =D
    Edited by: KaoroSorane on Aug 25, 2009 9:45 AM
    Edited by: KaoroSorane on Aug 25, 2009 11:05 AM

    Hi,
    Perhaps using ScalableGraphics could help you...
    No guarantees 'cause I'm just learning too but here's some pseudo code to play around with:
    final class SVGScreen extends MainScreen
    protected SVGImage _image;
    protected ScalableGraphics m_sg = ScalableGraphics.createInstance();
    int x_centerpoint;
    int y_centerpoint;
    //constructor
    SVGScreen()
        x_centerpoint = 100;
        y_centerpoint = 100;
        try {
                // Load our svg image.
                _image = loadSVGImage("/my_svg_file.svg");
        } catch (IOException e) {
                e.printStackTrace();
    }//end constructor
    public void paint(Graphics graphics) {
        m_sg.bindTarget(graphics);
        m_sg.render(x_centerpoint, y_centerpoint,_image);
        m_sg.releaseTarget();
    }//end paint
         * Loads an SVGImage from a given URL.
         * @param url The path to the svg image we want to load.
         * @return The loaded svg image.
        private SVGImage loadSVGImage(String url) throws IOException
            // Open our input stream of the svg file we want to load.
            InputStream inputStream = getClass().getResourceAsStream(url);   
            // Load our svg image from the input stream.
            return (SVGImage)SVGImage.createImage(inputStream, null);
        }HTH
    B
    Edited by: blueinc on Sep 11, 2009 2:08 PM

  • How to change font/ font color etc in a graphic object using JCombobox?

    Hello
    My program im writing recently is a small tiny application which can change fonts, font sizes, font colors and background color of the graphics object containing some strings. Im planning to use Jcomboboxes for all those 4 ideas in implementing those functions. Somehow it doesnt work! Any help would be grateful.
    So currently what ive done so far is that: Im using two classes to implement the whole program. One class is the main class which contains the GUI with its components (Jcomboboxes etc..) and the other class is a class extending JPanel which does all the drawing. Therefore it contains a graphics object in that class which draws the string. However what i want it to do is using jcombobox which should contain alit of all fonts available/ font sizes/ colors etc. When i scroll through the lists and click the one item i want - the graphics object properties (font sizes/ color etc) should change as a result.
    What ive gt so far is implemented the jcomboboxes in place. Problem is i cant get the font to change once selecting an item form it.
    Another problem is that to set the color of font - i need to use it with a graphics object in the paintcomponent method. In this case i dnt want to create several diff paint.. method with different property settings (font/ size/ color)
    Below is my code; perhaps you'll understand more looking at code.
    public class main...
    Color[] Colors = {Color.BLUE, Color.RED, Color.GREEN};
            ColorList = new JComboBox(Colors);
    ColorList.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ev) {
                     JComboBox cb = (JComboBox)ev.getSource();
                    Color colorType = (Color)cb.getSelectedItem();
                    drawingBoard.setBackground(colorType);
              });;1) providing the GUI is correctly implemented with components
    2) Combobox stores the colors in an array
    3) ActionListener should do following job: (but cant get it right - that is where my problem is)
    - once selected the item (color/ font size etc... as i would have similar methods for each) i want, it should pass the item into the drawingboard class (JPanel) and then this class should do the job.
    public class DrawingBoard extends JPanel {
           private String message;
           public DrawingBoard() {
                  setBackground(Color.white);
                  Font font = new Font("Serif", Font.PLAIN, fontSize);
                  setFont(font);
                  message = "";
           public void setMessage(String m) {
                message = m;
                repaint();
           public void paintComponent(Graphics g) {
                  super.paintComponent(g);
                  //setBackground(Color.RED);
                  Graphics2D g2 = (Graphics2D) g;
                  g2.setRenderingHint             
                  g2.drawString(message, 50, 50);
           public void settingFont(String font) {
                //not sure how to implement this?                          //Jcombobox should pass an item to this
                                   //it should match against all known fonts in system then set that font to the graphics
          private void settingFontSize(Graphics g, int f) {
                         //same probelm with above..              
          public void setBackgroundColor(Color c) {
               setBackground(c);
               repaint(); // still not sure if this done corretly.
          public void setFontColor(Color c) {
                    //not sure how to do this part aswell.
                   //i know a method " g.setColor(c)" exist but i need to use a graphics object - and to do that i need to pass it in (then it will cause some confusion in the main class (previous code)
           My problems have been highlighted in the comments of code above.
    Any help will be much appreciated thanks!!!

    It is the completely correct code
    I hope that's what you need
    Just put DrawingBoard into JFrame and run
    Good luck!
    public class DrawingBoard extends JPanel implements ActionListener{
         private String message = "message";
         private Font font = new Font("Serif", Font.PLAIN, 10);
         private Color color = Color.RED;
         private Color bg = Color.WHITE;
         private int size = 10;
         public DrawingBoard(){
              JComboBox cbFont = new JComboBox(GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames());
              cbFont.setActionCommand("font");
              JComboBox cbSize = new JComboBox(new Integer[]{new Integer(14), new Integer(13)});
              cbSize.setActionCommand("size");
              JComboBox cbColor = new JComboBox(new Color[]{Color.BLUE, Color.RED, Color.GREEN});
              cbColor.setActionCommand("color");
              JComboBox cbBG = new JComboBox(new Color[]{Color.BLUE, Color.RED, Color.GREEN});
              cbBG.setActionCommand("bg");
              add(cbFont);
              cbFont.addActionListener(this);
              add(cbSize);
              cbSize.addActionListener(this);
              add(cbColor);
              cbColor.addActionListener(this);
              add(cbBG);
              cbBG.addActionListener(this);
         public void setMessage(String m){
              message = m;
              repaint();
         protected void paintComponent(Graphics g){
              super.paintComponent(g);
              Graphics2D g2 = (Graphics2D)g;
              g2.setColor(bg);//set background color
              g2.fillRect(0,0, getWidth(), getHeight());          
              g2.setColor(color);//set text color
              FontRenderContext frc = g2.getFontRenderContext();
              TextLayout tl = new TextLayout(message,font,frc);//set font and message
              AffineTransform at = new AffineTransform();
              at.setToTranslation(getWidth()/2-tl.getBounds().getWidth()/2,
                        getWidth()/2 + tl.getBounds().getHeight()/2);//set text at center of panel
              g2.fill(tl.getOutline(at));
         public void actionPerformed(ActionEvent e){
              JComboBox cb = (JComboBox)e.getSource();
              if (e.getActionCommand().equals("font")){
                   font = new Font(cb.getSelectedItem().toString(), Font.PLAIN, size);
              }else if (e.getActionCommand().equals("size")){
                   size = ((Integer)cb.getSelectedItem()).intValue();
              }else if (e.getActionCommand().equals("color")){
                   color = (Color)cb.getSelectedItem();
              }else if (e.getActionCommand().equals("bg")){
                   bg = (Color)cb.getSelectedItem();
              repaint();
    }

  • Trying to move a graphics object using buttons.

    Hello, im fairly new to GUI's. Anyway I have 1 class which makes my main JFrame, then I have another 2 classes, one to draw a lil square graphics component (which iwanna move around) which is placed in the center of my main frame and then another class to draw a Buttonpanel with my buttons on which is placed at the bottom of my main frame.
    I have then made an event handling class which implements ActionListner, I am confused at how I can get the graphics object moving, and where I need to place the updateGUI() method which the actionPerformed method calls from inside the event handling class.
    I am aware you can repaint() graphics and assume this would be used, does anyone have a good example of something simular being done or could post any help or code to aid me, thanks!

    Yeah.. here's an example of custom painting on a JPanel with a box. I used a mouse as it was easier for me to setup than a nice button panel on the side.
    Anyways... it should make it pretty clear how to get everything setup, just add a button panel on the side. and use it to move the box instead of the mouse.
    -Js
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.event.MouseEvent;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.event.MouseInputAdapter;
    public class MoveBoxAroundExample extends JFrame
         private final static int SQUARE_EDGE_LENGTH = 40;
         private JPanel panel;
         private int xPos;
         private int yPos;
         public MoveBoxAroundExample()
              this.setSize(500,500);
              this.setDefaultCloseOperation(javax.swing.JFrame.EXIT_ON_CLOSE);
              this.setContentPane(getPanel());
              xPos = 250;
              yPos = 250;
              this.setVisible(true);     
         private JPanel getPanel()
              if(panel == null)
                   panel = new JPanel()
                        public void paintComponent(Graphics g)
                             super.paintComponent(g);
                             g.setColor(Color.RED);
                             g.fillRect(xPos-(SQUARE_EDGE_LENGTH/2), yPos-(SQUARE_EDGE_LENGTH/2), SQUARE_EDGE_LENGTH, SQUARE_EDGE_LENGTH);
                   MouseInputAdapter mia = new MouseInputAdapter()
                        public void mousePressed(MouseEvent e)
                            xPos = e.getX();
                            yPos = e.getY();
                            panel.repaint();
                        public void mouseDragged(MouseEvent e)
                            xPos = e.getX();
                            yPos = e.getY();
                            panel.repaint();
                   panel.addMouseListener(mia);
                   panel.addMouseMotionListener(mia);
              return panel;
         public static void main(String args[])
              new MoveBoxAroundExample();
    }

  • Querying for a script insert multiple selected objects...

    Is there a script or plugin which insert multiple selected objects in one new text frame with one click?
    And is there a script or plugin which extract the content of anchored text frame out it's frame and replace it with it's frame. and extract selected text and insert it inside a new anchored text frame in it's place? (like convert text to table - convert table to text, but instead table we use text frame)

    Hi,
    Using OMB scripting to set attribute properties in a data mapping sort of defeats the purpose of utilizing a graphical user interface to define and set properties for a data mapping? Surely the GUI data mapping tool was created to get away from writing scripts and scripting would also require that you know the name of the data mapping, table operator and the set of attribute names for which you have to write one line of script to set each property value, i.e. 90 lines to set 90 attribute values.
    Cheers,
    Phil

  • Image in a Graphics object

    Hi, I'm dealing with the Batik API for working with svg images, but I need to do some wmf imager representation too.
    This API offers a class which is able to read WMF files, giving a "WMFRecordStore", that you can use to initialize a "WMFPainter".
    Anyway, this WMFPainter class has a "paint" method which I hoped that I could use to print the wmf info in the screen but... I don't know if it can be done.
    You must pass a Graphics object to the "paint" method.
    If I want to add an image to a JLabel, as I'd do with an ImageIcon, do I have to get the current JLabel Graphics object? Will the image keep displayed when repainting? Is this a correct way of doing this?
    thanks a lot

    if you have to paint special things on a component, you have to subclass the component and override the paint (or paintComponent) method. You don't want to be getting the graphics object from a component and draw on it, it's not going to work properly.

  • I cant get it to work! NullPointerExeption at first awt.Graphics Object

    I am writing a game with AWT having it as an applet. I intend NOT to use anything outside of Java 1.1
    For my Game i thought that i ATLEAST need the following classes:
    MainGame, Level, Unit.
    I Started writing Level. wrote a fewe methods for it such as
    drawGras(int grastype) And started to write MainGame to see if they would work together. it's is/is going to be my first Java application where i actually know what object orienting is... I have already wrote a game in Java but with out knowing what a class or what object orienting realy is(the game works rather good to) but this time i wanted to use object orienting but came up with problems =( if first posted in "New to Javaprogramming" but they couldn't help me and advice me here
    My previous post: http://forum.java.sun.com/thread.jsp?forum=54&thread=290558
    Here's my code:
    import java.awt.*;
    public class MainGame extends java.applet.Applet
         implements Runnable {
         Thread runner;
         Image ImgLevel, ImgUnit;
         public MainGame() {
              Level nr1 = new Level();
              nr1.init();
              nr1.setGround(300);
              nr1.drawGras(1);
              nr1.CalcGraphics();
              nr1.drawSky(1);
              Image ImgLevel = nr1.getLevelImage();
         public void paint(Graphics g) {
              g.drawImage(ImgLevel,0,0,this);
         public void update(Graphics g) {
              paint(g);
         public void init() {
              MainGame Game = new MainGame();
         public void stop() {
              runner = null;
              System.exit(1);
         public void start() {
              if(runner == null) {
                   runner = new Thread(this);
                   runner.start();
         void Pause(int time) {
             try {
                 Thread.sleep(time);
             } catch(InterruptedException e) {
               System.out.println(e.toString());
         public void run() {
              Thread thisThread = Thread.currentThread();
                   while(thisThread == runner) {
    class Level extends java.applet.Applet {
        Font BigText = new Font("Arial", Font.PLAIN, 36);
        Font Normal = new Font("Arial", Font.PLAIN, 14);
        Font Bold = new Font("Arial", Font.BOLD, 14);
        Graphics GrLevel;
        int pattern, sky, GroundtoWalk, Ground;
        Color BgColor = new Color(166,202,240);
        Color gras1 = new Color(0,255,0);
        Color gras2 = new Color(0,200,0);
        Color gras3 = new Color(0,100,0);
        Image ImgLevel;
        void setBgColor(int r, int g, int b) {
            BgColor = new Color(r,g,b);
        void CalcGraphics() {
            ImgLevel = createImage(800,600);
            GrLevel = ImgLevel.getGraphics();
        void setGround(int GrounD) {
            Ground = GrounD;
        void GroundToWalkADD(int addToGround) {
            GroundtoWalk = Ground + addToGround;
        void setGroundToWalk(int GrToWalk) {
            GroundtoWalk = GrToWalk;
        public void init() {
              System.out.println("Init 1"); // This was placed here when i was checking how far it got when debuging
              CalcGraphics();
              System.out.println("Init 2");
              drawGras(1);
              System.out.println("Init 3");
              repaint();
              System.out.println("Init 4");
        Image getLevelImage() {
            return ImgLevel;
        public void paint(Graphics g) {
              g.drawImage(ImgLevel,0,0,this);
        public void update(Graphics g) {
            paint(g);
        void drawGras(int pt) {
         GrLevel.setColor(BgColor);
         GrLevel.fillRect(0,0,800,600);
         switch(pt) {
              case 1:
                   GrLevel.setColor(gras1);
                   GrLevel.fillRect(0,GroundtoWalk,800,300);
                   GrLevel.setClip(0,GroundtoWalk,800,300);
                   for(int i = 0; 890>i;i=i+5) {
                        GrLevel.setColor(gras2);
                        GrLevel.drawLine(0+i,GroundtoWalk,-190+i,GroundtoWalk+300);
                   for(int i=950; 0<i; i=i-5) {
                        GrLevel.setColor(gras3);
                        GrLevel.drawLine(890-i,GroundtoWalk,1000-i,GroundtoWalk+300);
              break;
              case 2:
                   GrLevel.setColor(gras2);
                   GrLevel.fillRect(0,GroundtoWalk+5,800,300);
                   for(int i = 0; 890>i;i=i+5) {
                        GrLevel.setColor(gras3);
                        GrLevel.drawLine(0+i,GroundtoWalk,-190+i,GroundtoWalk+300);
                   for(int i=950; 0<i; i=i-5) {
                        GrLevel.setColor(gras1);
                        GrLevel.drawLine(890-i,GroundtoWalk,1000-i,GroundtoWalk+300);
              break;
              case 3:
                   GrLevel.setColor(gras3);
                   GrLevel.fillRect(0,GroundtoWalk+10,800,300);
                   for(int i = 0; 800>i; i=i+20) {
                        GrLevel.fillArc(0+i,GroundtoWalk,20,20,180,-180);
              break;
         pattern = pt;
        int getGrasPattern() {
             return pattern;
        void drawSky(int cl) {
                GrLevel.setColor(BgColor);
                GrLevel.fillRect(0,0,800,155);
                switch(cl) {
                    case 1:
                   for(int y = 0;y<7;y++) {
                   for(int x = 0;x<800;x=x+20) {
                                GrLevel.setColor(Color.white);
                                GrLevel.drawArc(x,y*20,20,20,180,180);
                                GrLevel.setColor(Color.red);
                                GrLevel.drawArc(x,y*20+4,20,20,180,180);
                                GrLevel.setColor(Color.yellow);
                                GrLevel.drawArc(x,y*20+2,20,20,180,180);
                                GrLevel.setColor(Color.green);
                                GrLevel.drawArc(x,y*20+8,20,20,180,180);
                                GrLevel.setColor(Color.blue);
                                GrLevel.drawArc(x,y*20+12,20,20,180,180);
                                GrLevel.setColor(Color.pink);
                                GrLevel.drawArc(x,y*20+16,20,20,180,180);
              break;
              case 2:
                        GrLevel.setColor(Color.gray);
              break;
         sky = cl;
         GrLevel.setFont(BigText);
         GrLevel.setColor(Color.black);
         GrLevel.fillRect(0,0,800,50);
         GrLevel.setColor(Color.white);
         GrLevel.drawString("Score Tabel - comming someday",((size().width)/2)-260, 40);
        int getSkyTyp() {
             return sky;
    }I tested running the code of class Level by puting it into Level.java and compiled it...ran it with appletviewer and it worked as it was intended to.
    But when i compiled it with MainGame... and in the HTML started MainGame.class,.....applet didn't intializeand i got the following error messege:
    Init 1
    java.lang.NullPointerException
            at Level.CalcGraphics(MainGame.java:84)
            at MainGame.<init>(MainGame.java:11)Line 82: void CalcGraphics() {
    Line 83: ImgLevel = createImage(800,600);
    Line 84: GrLevel = ImgLevel.getGraphics(); // The First awt.Graphics object
    Line 85: }
    Line 9:      public MainGame() {
    Line 10:     Level nr1 = new Level();
    Line 11:     nr1.CalcGraphics(); // calling the method above -> same error first awt.Graphics Object.
    If i change it os that "drawGras" comes first it's first awt.Graphics Line will show the same error
    Hope some one can and will help me

    As per the documentation of
    java.awt.Component.createImage(int,int):
    Creates an off-screen drawable image to be used for
    double buffering.
    Parameters:
    width - the specified width
    height - the specified height
    Returns:
    an off-screen drawable image, which can be used for
    double buffering. The return value may be null if the
    component is not displayable. This will always happen
    if GraphicsEnvironment.isHeadless() returns true.
    Since:
    JDK1.0 its not
    ImgLevel = createImage(800,600); that's making the problem but The first awt.Graphics Object in class Level, no mather which on it is =((
    >
    The key part is '...may be null if the component is
    not displayable.'
    You should put your graphics initialization code in
    start(), which will be called when your applet is
    ready to go. Before then, your applet is not
    displayable. (Also, remember to dispose() your
    graphics in your stop() method, if not sooner.)for the part writen above...I'll try to change it like you are saying.
    Thanx for your help!

  • How must I initialize a graphics object?

    Hi,
    I've a problem with Graphics Abstract class;
    how must I do to initialize a Graphics object?
    I must execute this code:
    Graphics gr;
    gr.drawString("Image",30,0);
    gr.drawString("not",30,30);
    gr.drawString("Found",30,60);
    image.paintIcon(null,gr,0,0);
    the compiler returns my the error:
    "gr not initialized"
    How can I do to initialize this last?
    Thank.

    Or you can call getGraphics() on any Component, but most likely you will do any graphics in the paint method as tjacobs said.

  • Printing graphics object in Landscape or portrait mode

    Hello,
    I have a graphics 2d object (a Tree Diagram) which is inside a JScrollPane,and the JSCrollPane is on a JPanel. it's length and width is more than one page. I am using a printable object to print the object. The task I need to do is,
    (1). compress the width and length of the diagram, so that if can fit into one page, else split the diagram into pages, so that each part of it can be printed on different pages(page size A4) and then later those pages can be merged accordingly.
    I am not able to find, how to split the graphic object(the tree diagram into pages), shoul d I try doing it using x and y co ordinate of the graphic object.

    * PrintUtilities.java
    * Created on January 17, 2007, 7:25 PM
    * To change this template, choose Tools | Template Manager
    * and open the template in the editor.
    package action.vector.bam;
    * @author serjith
    import java.awt.*;
    import javax.swing.*;
    import java.awt.print.*;
    import javax.print.attribute.HashPrintRequestAttributeSet;
    import javax.print.attribute.PrintRequestAttributeSet;
    /** A simple utility class that lets you very simply print
    * an arbitrary component. Just pass the component to the
    * PrintUtilities.printComponent. The component you want to
    * print doesn't need a print method and doesn't have to
    * implement any interface or do anything special at all.
    * <P>
    * If you are going to be printing many times, it is marginally more
    * efficient to first do the following:
    * <PRE>
    * PrintUtilities printHelper = new PrintUtilities(theComponent);
    * </PRE>
    * then later do printHelper.print(). But this is a very tiny
    * difference, so in most cases just do the simpler
    * PrintUtilities.printComponent(componentToBePrinted).
    * 7/99 Marty Hall, http://www.apl.jhu.edu/~hall/java/
    * May be freely used or adapted.
    public class PrintUtilities implements Printable {
    private Component componentToBePrinted;
    public static void printComponent(Component c) {
    new PrintUtilities(c).print();
    public PrintUtilities(Component componentToBePrinted) {
    this.componentToBePrinted = componentToBePrinted;
    public void print() {
    PrinterJob printJob = PrinterJob.getPrinterJob();
    PrintRequestAttributeSet set = new HashPrintRequestAttributeSet();
    PageFormat pgFormat = printJob.pageDialog(set);
    printJob.setPrintable(this,pgFormat);
    //printJob.setPrintable(this);
    if (printJob.printDialog())
    try {
    printJob.print();
    } catch(PrinterException pe) {
    System.out.println("Error printing: " + pe);
    public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
    if (pageIndex > 0) { // requires change since it is bigger than a single page
    return(NO_SUCH_PAGE);
    } else {
    Graphics2D g2d = (Graphics2D)g;
    g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    disableDoubleBuffering(componentToBePrinted);
    int W = componentToBePrinted.getWidth();
    int H = componentToBePrinted.getHeight();
    //Component newComp = componentToBePrinted.getGraphics().clipRect();
    System.out.println("WorkSpace Height "+H+" Width "+W);
    pageFormat.getHeight();
    pageFormat.getWidth();
    pageFormat.setOrientation(PageFormat.LANDSCAPE);
    //componentToBePrinted.paint(g2d);
    componentToBePrinted.printAll(g2d);//.paintAll(g2d);
    enableDoubleBuffering(componentToBePrinted);
    return(PAGE_EXISTS);
    /** The speed and quality of printing suffers dramatically if
    * any of the containers have double buffering turned on.
    * So this turns if off globally.
    * @see enableDoubleBuffering
    public static void disableDoubleBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(false);
    /** Re-enables double buffering globally. */
    public static void enableDoubleBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(true);
    =============================================================
    Please find this code, which I am trying to use, here I am passing the JPanel
    try{                   
    PrintUtilities.printComponent(actWorkSpace);
    }catch(Exception ex){
    ex.printStackTrace();
    the actWorkSpace is a JPanel with graphics as mentioned above, which is being passes to PrintUtilities.printComponent();
    the output is only just a single page with just a portion of the graphics on the JPanel, pls help...... it is urgent....

  • Accessing graphics object?

    Hi,
    I was wondering, is the only place the graphics object relevent inside the paintComponent method?
    I'm asking because I have a method that draws a custom progress bar. I have another method that draws that progress bar filling up over a arbitrary period of time. I want to use Thread.sleep() to provide a delay between redraws.
    Now I have the first method inside the paintComponent() method of a JPanel. Thats fine, works great! Now I didn't want to put the redraw method inside the paintComponent because the Thread delay will manifest itself in the painting of the component. So I thought I could solve this by making the second method a public one and using the getGraphics() method of the JPanel call the method once the object is instantiated. However this gives me a NullPointerException as soon as the method calls on the graphics object. Any ideas where I'm going wrong? Thanks!
    Method inside extended JPanel object
    public void testRun(Graphics g)
            // Cast to Graphics2D
            Graphics2D g2 = (Graphics2D)g;
            while(percentComplete < 100)
                try {
                    Thread.sleep(30);
                } catch (java.lang.InterruptedException ie) {
                    System.err.println("We got a problem");
                drawProgressBar(g2,percentComplete);
                percentComplete += 1;+
    +        }+
    +        percentComplete+ = 1;
            drawProgressBar(g2,percentComplete); // contains a repaint() method call to object
        }This inside the method of another object
    private void setupContentPanel()
            cpb = new CustomProgressBar();
            mainWindow.add(pb, BorderLayout.CENTER);
            cpb.testRun( pb.getGraphics() );
        }

    No, don't use update(...), that's not at all what the method is for. Also, avoid getGraphics() like the plague.
    What you need to do is increment an instance field using a Swing Timer, and invoke repaint(). The paintComponent override should use the current value of the instance field for appropriate painting. Example:import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.*;
    public class PseudoProgressBar {
       int progress = 0;
       JPanel panel= new JPanel() {
             @Override
             protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.setColor(Color.BLUE);
                int w = getWidth();
                int h = getHeight();
                g.fillRect(0, h/2-10, (w * progress)/100, 20);
       public static void main(String[] args) {
          SwingUtilities.invokeLater(new Runnable() {
             @Override
             public void run() {
                new PseudoProgressBar().makeUI();
       public void makeUI() {
          JFrame frame = new JFrame();
          frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          frame.setSize(400, 100);
          frame.setContentPane(panel);
          frame.setLocationRelativeTo(null);
          frame.setVisible(true);
          new Timer(100, new ActionListener() {
             public void actionPerformed(ActionEvent e) {
                progress %= 100;
                progress++;
                panel.repaint();
          }).start();
    }db

  • Create a graphics object

    Hello,
    I want to create a graphics object. However, I need to use it in a function outside of a paint method in an applet.
    I need to create the object to check the FontMetrics of a combination of font parameters. This needs to be done independent of an applet. The problem is I want to use fontMetrics but not in an applet. I need to test the width and height of a message, which will eventually be used in an applet. However, this needs to be done before the applet receives the font.
    Can I create a graphics object outside of a paint method to check the fontMetrics of a combination of fonts? If not, can I check FontMetrics without a graphics object?

    Ok, by "graphic", when you say "I need to test whether one graphic will fit inside another", do you mean an instance of the Image class? If so (sorry, I thought you were wondering if you could create a "Graphics" object for use in calculating the Font Metrics) then you can use the stuff in the javax.imageio package to read your image, or, if you're not at 1.4 yet, do something like:
    image = new ImageIcon("image.gif").getImage();
    // Get the dimensions of the image; these will be non-negative
    width = image.getWidth(null);
    height = image.getHeight(null);to get the dimensions of your images.
    Hope that helped
    Lee

  • Saving Graphics Object

    Is it possible to transfer a Graphics Object to another Canvas so that I can use the painted graphics there?
    I have a canvas, where some texts and boxes are painted. Now I want to start another Canvas, where the user can move a Pointer in the Graphic of the other Canvas.
    So I thought I hand over the Graphics-Object to my new Canvas and overwrite my actual Graphics-Object. Now I want to paint a crosspointer and move it on the screen.
    I hope anyone has understood this stupid question.
    Great_T

    You have to use "manual" double buffering:
    private Image image = Image.creaneImage(this.getWeight(), this.getHeight());
    private Graphics graphics = image.getGraphics();
    Paint to graphics.
    public void paint(Graphics g) {
    g.drawImage(image, 0, 0, Graphics.TOP | Graphics.LEFT);
    Then pass your image in the new Canvas and continue to paint to it's
    Graphics object
    I hope this is helpful.

Maybe you are looking for

  • Message Send from ABAP Proxy implemented in XI Server ABAP Stack

    Hello everyone, I have a question and I'm not sure of this is an ABAP question but I'll try here and try to find some information on ABAP forums and weblogs, I need to send a XML message to the XI pipeline from an ABAP Server Proxy implemented in the

  • Privacy on website information acquisition.

    I recently saw the issues of Facebook that generated concerns for privacy, but recently I was browsing a WordPress blog and got very worried of how much information it got from my PC. Seeing what Google did with the Doodle that could gather informati

  • Condition isn't working properly

    hi, in MM pricing in subcontracting issue i want to add additional value on material price for that i create Z condition type but when i am inputing the value manually it is not adding in base price. The same procedure is working fine in devlopment b

  • Searchability & metadata extraction on password protected or compressed PDFs

    Hello, I am currently putting together a new document management system at my company (using http://www.alfresco.com ) and part of the functionality will involve automatic metadata extraction from stored PDFs, and google-like full-text search of PDFs

  • Torrents, how do I open ports

    I have a Netgear DG934G Router from Sky which is broadcasting a 'B/G' only network. To this, connected by ethernet I have an Airport Extreme which runs a seperate 'N' only network. The Extreme is set to bridge and the Netgear distributes the IP addre