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.

Similar Messages

  • Is there a way to initialize a Graphics object (indirectly)?

    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.

    Infact with
    gr=null;
    i've a null pointer exception;
    but I've also try
    jLabel2.setText("Prova");
    Graphics gr = jLabel2.getGraphics();
    gr.drawString("Image",30,0);
    gr.drawString("not",30,30);
    gr.drawString("Found",30,60);
    image.paintIcon(this,gr,0,0);
    jLabel3.setIcon(image);
    and I've always a null pointer exception.
    Why?
    Thank.

  • How does one Float a Graphic Object with Text? (Don't want the Graphics Frame stationary)

    I now know just enough InDesign to be dangerous.  So, help me from blowing myself up.
    SITUATION:
    I desire a Callout/Quote Box to emphase a quote--to separate it from the flowing text of the manuscript.  So, I created a curved-edge rectangle (graphic object) to make the "box", then filled it with the quoted text).  All was well in the land of Adobe Novice UNTIL I deleted some text above the newly-created graphic box/quote box.  I need the graphic to flow with (stay embedded in; hold its position in) the text outside the manuscript, not say anchored to page.
    QUESTION:
    Is there a way to have a graphic object which is placed in a manuscript flow with the manuscript text, so that it "holds its position" relative to the text.  For example, if I delete a paragraph of text above the graphic object, I want the graphic object to adjust accordingly.
    ASIDE:
    I am open to any other tricks or methods others use to insert callout or quote-boxes within the flowing text of a manuscript/book.
    Thanks in advance.

    Create your callout. If you will use it often, you can actually grab it and drag it to the desktop for reuse in any Document; it becomes an InDesign Snippet (.inds).
    Copy the callout graphic, insert your text curser into the text frame where you want the callout. You've just Anchored an Object.
    This is where you want to read up on Anchored Objects. You can highlight and baseline shift the callout (often necessay for anchored objects) , change leading, apply text wrap with standoff (you would select it with the selection tool for this), all of which are way beyond what I have ever tried, but managed it in less than 3 minutes. Basically treat it as a selection of type. The challenges will be line breaks, keep with, gosh knows.
    Bob mentioned CS5.5 has more friendly features, which I am not familiar with, and are beyond quick replies.
    Work through the above at your discretion, ask more DIRECT questions as needed, and you will get help. 

  • 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();
    }

  • Can I modify a e.g. drawCircle Graphics object?

    I have a Sprite in which I have drawn a circle with a fill.  Later on, I wish to modify the color of this circle.  I have retrieved the Graphics object from the Sprite using getChildAt(), and have tried:
    getChildAt(i).graphics.beginFill(0x550000);
    however this does not work.
    Is this possible?  I've RTFM'd but can't figure out exactly how to deal with the Graphics object.
    Thanks!

    you need to re-draw the circle.
    sp.graphics.beginFill(0x550000);
    sp.graphics.drawCircle(x,y,rad);   // <--assign values
    sp.graphics.endFill()

  • Passing Graphics object

    Trying to do an exercise which states that methodX should draw a square of a specific size according to a value input by the user.
    Unsure about the following
    "methodX should be called from the applets paint method and should be passed the Graphics object from paint".
    How do I pass the Graphics object?
    Thanks.
    Alan

    The paint method has one parameter, Graphics. So you over-ride the patient() method like so, and call your method passing the Graphics object:
    public void paint(Graphics g)
    methodX(g);
    and in methodX
    public void methodX(Graphics g)
    g.drawRect(100, 100, 100, 100);
    This doesn't take the size from the user, but shows how to do the pass from paint(). Hope this helps

  • Java app Graphics object help

    Hey, how do I get a graphics object in a Java application? In an applet, the entire thing's a graphics object. I want to somehow draw stuff onto a JPanel or something of the like. How do I do this?!?!?

    you need to overload the paint() method inherited from java.awt.Component , for example:
    public void paint(Graphics g) {
      g.setColor(new java.awt.Color(0,0,255));
      g.fillRect(0, 0, getWidth() - 1, getHeight() - 1);
    }note that this will totally override the look of the component. I'm not sure whether you can call super.paint() in the event that you are extending a panel or other non-abstract AWT or Swing component.
    McF

  • 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();
    }

  • How to use a Graphics Object in a JSP?

    Hello, I do not know if this is a good or a silly question. Can anyone tell me if we can use a Graphics object in a JSP. For example to draw a line or other graphics, i am planning to use the JSP. Any help is much appreciated.
    Regards,
    Navin Pathuru.

    Hi Rob or Jennifer, could you pour some light here.
    I have not done a lot of research for this, but what i want to do is below the polygon i would like to display another image object like a chart... is it possible? If so how to do it? Any help is much appreciated.
    here is the code:
    <%
    // Create image
    int width=200, height=200;
    BufferedImage image = new BufferedImage(width,
    height, BufferedImage.TYPE_INT_RGB);
    // Get drawing context
    Graphics g = image.getGraphics();
    // Fill background
    g.setColor(Color.white);
    g.fillRect(0, 0, width, height);
    // Create random polygon
    Polygon poly = new Polygon();
    Random random = new Random();
    for (int i=0; i < 5; i++) {
    poly.addPoint(random.nextInt(width),
    random.nextInt(height));
    // Fill polygon
    g.setColor(Color.cyan);
    g.fillPolygon(poly);
    // Dispose context
    g.dispose();
    // Send back image
    ServletOutputStream sos = response.getOutputStream();
    JPEGImageEncoder encoder =
    JPEGCodec.createJPEGEncoder(sos);
    encoder.encode(image);
    %>
    Regards,
    Navin Pathuru

  • How to initialize a Type Object??

    Hi,
    I have a procedure as below, which has type t_r_rep_data and a table having this type as record, but when I called this procedure, it has ORA-06530 error: Reference to uninitialized composite. Can you tell me how to initialize a type Object?
    Also, is it this the right way to insert a type record into the table, or can I just just INSERT statement?
    Many thanks
    PROCEDURE add_row
    ( in_row_type_ind CHAR,
    in_ordering VARCHAR2
    ,in_record_type VARCHAR2
    ,in_level1_value VARCHAR2
    ,in_level1_description VARCHAR2
    ,in_level2_value VARCHAR2
    ,in_level2_description VARCHAR2
    ,in_level3_value VARCHAR2
    ,in_level3_description VARCHAR2
    ,in_level4_value VARCHAR2
    ,in_level4_description VARCHAR2
    ,in_amount_as_of_date1 NUMBER
    ,in_amount_as_of_date2 NUMBER
    ,io_table IN OUT t_ntr_rep_data
    IS
    l_row_count NUMBER;
    l_row t_r_rep_data;
    BEGIN
    -- ??? not sure where and how to do the initialization bit
    l_row.row_type_ind := NULL;
    l_row.ordering := NULL;
    l_row.record_type := NULL;
    l_row.level1_value := NULL;
    l_row.level1_description := NULL;
    l_row.level2_value := NULL;
    l_row.level2_description := NULL;
    l_row.level3_value := NULL;
    l_row.level3_description := NULL;
    l_row.level4_value := NULL;
    l_row.level4_description := NULL;
    l_row.amount_as_of_date1 := 0;
    l_row.amount_as_of_date2 := 0;
    SELECT COUNT(*)
    INTO l_row_count
    FROM (TABLE(CAST(io_table AS t_ntr_rep_data)));
    l_row.row_type_ind := in_row_type_ind;
    l_row.ordering := in_ordering;
    l_row.record_type := in_record_type;
    l_row.level1_value := in_level1_value;
    l_row.level1_description := in_level1_description;
    l_row.level2_value := in_level2_value;
    l_row.level2_description := in_level2_description;
    l_row.level3_value := in_level3_value;
    l_row.level3_description := in_level3_description;
    l_row.level4_value := in_level4_value;
    l_row.level4_description := in_level4_description;
    l_row.amount_as_of_date1 := in_amount_as_of_date1;
    l_row.amount_as_of_date2 := in_amount_as_of_date2;
    io_table(l_row_count+1) := l_row;
    END;
    --------------------------------------------------

    Simply write a stud which queries the Oracle Dictionary tables which will return Object Type
    Based on the object_name and User_name

  • How can I run graphic object on report. ( I got REP-1246 Chart not found)

    Hi All,
    I made a report that consists a chart object. When I run it on report builder, it works well. But When I call the report from client side, I got "Rep-1246 Char Document not found" . I tried to solve it , I couldn't solve the problem . If I delete chart object from report , then report works well on client side. I didn't use graphics builder to create graphs I used only report builder to do it. I read the threads about it , but I couldn't find the solution. All solutions are about path of graphic file. I don't understand it. Because I only have *.rdf *.rep file. There is no any graph file in my system. I can create it in graphic builder but I don't know how can I deploy the graph object into report layout and run ?
    I need urgent help ..
    Thanks in advice
    Suleyman

    Hi again , I used developer 2000. In order to show graphic object on report firstly
    I created my graphic object on oracle graph builder.After that I save it like mygraph.OGD . Then I added graphic object on report builder by using graphic object on report builder. When you click the graphic object you will see CHART FILENAME part in part of CHART. In this field , you should add graphic file path that you created on graphic builder. I added mygraph.OGD into this filename part. I worked well.
    Good LUck !

  • How to convert a Graphics object into a JPG image?

    I have this simple question about how to make a Graphics object into a JPG file...
    I just need the names of the classes or the packages ... I'll figure out the rest of the details...
    Thanks...

    Anyway this might come in handy
    JPEGUtils.java
    ============
    * Created on Jun 22, 2005 by @author Tom Jacobs
    package tjacobs.jpeg;
    import java.awt.Image;
    import java.awt.image.BufferedImage;
    import java.awt.image.RenderedImage;
    import java.io.BufferedInputStream;
    import java.io.BufferedOutputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import javax.imageio.ImageIO;
    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;
    * Utilities for saving JPEGs and GIFs
    public class JPEGUtils {
         private JPEGUtils() {
              super();
         public static void saveJPEG(BufferedImage thumbImage, File file, double compression) throws IOException {
              BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file));
              saveJPEG(thumbImage, out, compression);
              out.flush();
              out.close();
         public static void saveJPEG(BufferedImage thumbImage, OutputStream out, double compression) throws IOException {
              JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
              JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(thumbImage);
              compression = Math.max(0, Math.min(compression, 100));
              param.setQuality((float)compression / 100.0f, false);
              encoder.setJPEGEncodeParam(param);
              encoder.encode(thumbImage);
         public static BufferedImage getJPEG(InputStream in) throws IOException {
              try {
                   JPEGImageDecoder decode = JPEGCodec.createJPEGDecoder(in);
                   BufferedImage im = decode.decodeAsBufferedImage();
                   return im;
              } finally {
                   in.close();
         public static BufferedImage getJPEG(File f) throws IOException {
              InputStream in = new BufferedInputStream(new FileInputStream(f));
              return getJPEG(in);
         public static void saveGif(RenderedImage image, File f) throws IOException {
              saveGif(image, new FileOutputStream(f));
         public static void saveGif(RenderedImage image, OutputStream out) throws IOException {
    //          Last time I checked, the J2SE 1.4.2 shipped with readers for gif, jpeg and png, but writers only for jpeg and png. If you haven't downloaded the whole JAI, and you want a writer for gif (as well as readers and writers for several other formats) download:
    //          http://java.sun.com/products/java-media/jai/downloads/download-iio.html
              ImageIO.write(image, "gif", out);
         public static void main(String[] args) {
              // TODO Auto-generated method stub
    }

  • How can I tell if a Graphics object has been disposed

    Any ideas?
    Thanks

    My goal is to find out if a graphics object has been disposed or not...
    ...but I'll play along. the application offers the user some nice graphics to amuse them, I use the Graphics object. In my endeavours, something isn't getting displayed where I expect it to, and I suspect that somewhere I'm accidentally disposing the graphics object. So, like checking for nulls, I want to debug the application and make sure the graphics context is as I expect.
    A bit of a side note, SWT will throw an exception if you try and use a "graphics" type object that has been disposed and has a method called, unsurprisingly enough, isDisposed(). Can you guess what it returns?

  • How to get name of a graphic object

    Hi all,
    i created various grids and graphic obejcts in a splitter container.
    Now i want to set focus ( cl_gui_control=>set_focus )on the graphics objects, but i dont know the control names. for the grid this is no problem, but as i created the graphics with the FM 'GFW_PRES_SHOW' i dont know their names..
    so, is there a simple way to get these object names?
    best regards
    dennis
    Message was edited by:
            Dennis Abmeier

    Hi Ralf,
    thanks for your reply!
    The container name doesnt help me, i tried already to focus the container. I think the problem is, that i have created 4 instances of different object types in the splitter container, so the focus is always on the first created instance (Layer?) in the container or the last focussed. As i write, focus the manually created instances(Grids) is no problem because i know their names.
    So what i need is the name of FM generated (Graphic) instance which lies in the splitter-container.

  • How to set tool tips for graphic objects.

    Hi
    i have a code like this
    here dst is graphic object but i casted ti Graphic2D object because i have to set back ground color.
    Graphics2D lGraphic = (Graphics2D) dst;
    lGraphic.setBackground(Color.RED);
    lGraphic.clearRect((int) lx, (int) ly, (int) lw + 1, (int) lh + 1);
    lGraphic.drawRect(0, 0, (int) lw, (int) lh);
    so now i want to set a tool tip for this lGraphic Object.
    can any body please post answer for this proble.
    if you will post in advance it will help me a lot.

    so now i want to set a tool tip for this lGraphic Object.Your concepts are all wrong. Read the API for java.awt.Graphics and try to understand that a Graphics object is akin to a paintbrush: it has methods to draw whatever is to be drawn. The painting is not the brush, the brush does the painting.
    To obtain a custom tooltip at certain locations within a JComponent, I think the easiest way is to override getToolTipText(MouseEvent me). The method can return null for locations where a tooltip is not to be shown.
    db

Maybe you are looking for

  • Error in post goods receipt

    Hi...... There is an error " Update Control of Movement Type is Incorrect (entry 161XX_L_V) when i create Post Goods Receipt. Need help Thanks

  • Cannot Convert PDF to Word

    Hi, I am attempting to convert a PDF to word.  I had another file the exact same size and essentially the same content, but the latest file is a corrected version of the first.  I need to compare the two word documents to insure no additional changes

  • I have installed Acrobat X PRO but cannot open my files. How canI open my files

    How can I access my files that I installed usin Acrobat X Professional?

  • No auto focus with SQ on native lens?

    Hi FS7 users, Wasn't sure if anyone else is running into this problem, but when using the native sony e mount in SQ mode, it does not auto focus at all. Even when using manual and clicking the "Focus Push Auto" button it does nothing. On the FS700 th

  • What is in version 3?

    I would like to know what SP level is the Discovery System version 3? Additionally, what software does version 3 contain which is not in version 2? Thanks, Tamas