How to call - draw(Graphics g)

This is a little method in my Applet:
public void draw(Graphics g)
g.drawImage(image, 0, 0, this);
What I want is to call this method when I need it, not automatically like paint(Graphics g), but I couldn't figure out how to call, because Graphics is abstract class, can not be instantiated .
Pleeeeeeeeeeeeease help me out , many thanks !!!

This is a little method in my Applet:
public void draw(Graphics g)
g.drawImage(image, 0, 0, this);
What I want is to call this method when I need it,Why?
not automatically like paint(Graphics g), but I
couldn't figure out how to call, because Graphics is
abstract class, can not be instantiated .Right. You can't, nor should you ever need to do what you want to do. The Graphics object is passed to you in the paint() method.
See:
http://java.sun.com/products/jfc/tsc/articles/painting/index.html

Similar Messages

  • How can get a Graphics to draw line on screen?

    How can get a Graphics to draw line on screen?
    Now, I can get a Graphics to draw line based on component. For example JPanel, but I want to get a Graphics to draw line on screen.

    By drawing on the screen, I assume you mean drawing outside the bounds of a top-level window like
    JFrame or JDialog. You can't do that. At least, without going native and even then that's a dodgey thing
    for any platform to let you do. One thing you can do is simulate it with a robot's screen capture:
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class X {
        public static void main(String[] args) throws Exception {
            Rectangle bounds = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
            BufferedImage image = new Robot().createScreenCapture(bounds);
            Graphics2D g2 = image.createGraphics();
            g2.setStroke(new BasicStroke(20));
            g2.setPaint(Color.RED);
            g2.drawLine(0, 0, bounds.width, bounds.height);
            g2.drawLine(bounds.width, 0, 0, bounds.height);
            g2.dispose();
            JLabel label = new JLabel(new ImageIcon(image));
            label.addMouseListener(new MouseAdapter(){
                public void mousePressed(MouseEvent evt) {
                    System.exit(0);
            JFrame f = new JFrame();
            f.setUndecorated(true);
            f.getContentPane().add(label);
            f.setBounds(bounds);
            f.setVisible(true);
    }

  • Calling paintComponent(Graphics g) in another class

    Dear Friends,
    I have a class (Class Pee) where I implemented the paintComponent(Graphics g) and another class (Class Bee) where I generate some datas. My intention is to call the paintComponent(Graphics g) method in class Pee at class Bee to make use of the generated data to draw some figures.
    I imported java.awt .Graphics, java.awt.Graphics2D, Polygon and geom and declared Graphics2D g2d = (Graphics2D) g; as well, but still when I call paintComponent (Graphics g) it fails to recognize the g. What is actually wrong.
    See code:
    Class Pee
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Polygon;
    import javax.swing.JPanel;
    public class Pee extends JPanel{
    private int offset;
    public void paintComponent(Graphics g, int b[], int c[]){
    super.paintComponent(g);
    Graphics2D g2D = (Graphics2D) g;
    this.setBackground(Color.white);
    Class Bee
        import java.io.*;
        import java.util.*;
        import java.awt.Graphics;
        import java.awt.Graphics2D;
        import java.awt.geom.*;
        import java.awt.Polygon;
       import Graphic.Pee; //importing Pee Class
    public class Bee{
    int x[];
    int y[];
    // other variable declaration
    public Bee{
    x = new int [5];
    y = new int [5];
    Pee dr = new Pee();
    Graphics2D g2d = (Graphics2D) g;
    //code to generate data
    dr.paintComponent(g,x,y);
    }It always say that "g" cannot be resolved. Please how do I get over this.
    Thanks,
    Jona_T

    Swing calls the paintComponent method when we ask a component to draw itself. We do this by
    calling its repaint method. So the general approach is to change the data in the component
    that does the graphics for us and then ask the component to repaint itself. Swing does the
    rest. One benefit of this way of doing things is that the graphic component keeps the data
    and can render all or any part of it at any time. Trying to get a reference to the
    components graphics context from within another class and using it to draw graphics in the
    graphics component prevents this and the foreign class event code can never know when the
    graphics component needs to be re–rendered.
    So the idea is to keep the graphics/rendering component independent from the event code. The
    event code controls the state (member variables) in the graphics component and tells it when
    to re–render itself.
    There are a lot of (creative) ways of putting these things together. Here's an example.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.Random;
    import javax.swing.*;
    public class CallingGraphics implements ActionListener {
        GraphicComponentClass graphicComponent;
        DataGenerationClass   dataGenerator = new DataGenerationClass();
        public void actionPerformed(ActionEvent e) {
            Point2D.Double[] data = dataGenerator.getData();
            graphicComponent.setData(data);
        private JPanel getGraphicComponent() {
            graphicComponent = new GraphicComponentClass();
            return graphicComponent;
        private JPanel getLast() {
            JButton button = new JButton("send data to graphics");
            button.addActionListener(this);
            JPanel panel = new JPanel();
            panel.add(button);
            return panel;
        public static void main(String[] args) {
            CallingGraphics test = new CallingGraphics();
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(test.getGraphicComponent());
            f.getContentPane().add(test.getLast(), "Last");
            f.setSize(400,300);
            f.setLocation(200,200);
            f.setVisible(true);
    class GraphicComponentClass extends JPanel {
        Ellipse2D.Double[] circles = new Ellipse2D.Double[0];
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            for(int j = 0; j < circles.length; j++) {
                g2.draw(circles[j]);
        public void setData(Point2D.Double[] p) {
            double w = getWidth();
            double h = getHeight();
            double dia = 75.0;
            circles = new Ellipse2D.Double[p.length];
            for(int j = 0; j < circles.length; j++) {
                double x = p[j].x*(w - dia);
                double y = p[j].y*(h - dia);
                circles[j] = new Ellipse2D.Double(x,y,dia,dia);
            repaint();
    class DataGenerationClass {
        Random seed = new Random();
        public Point2D.Double[] getData() {
            int n = seed.nextInt(25);
            Point2D.Double[] locs = new Point2D.Double[n];
            for(int j = 0; j < n; j++) {
                double x = seed.nextDouble();
                double y = seed.nextDouble();
                locs[j] = new Point2D.Double(x, y);
            return locs;
    }

  • How to call paint ( )?

    Hi,
    I am trying to display a tring but I dont know how to call paint ( ). I used show but its giving me mesg that show is deprecated.
    Can somebody help me in this regard?
    import java.awt.*;
    class DisplayText extends Frame{
    DisplayText (String s) {
      super(s);
    public void paint (Graphics g) {
      g.drawString("Hello World", 10,10);
    public static void main (String args[ ]) {
       DisplayText screen = new DisplayText("Example 1");
                screen.setSize(500,100);
                screen.setVisible(true);
    }Zulfi.

    I don't really recommend using the paint() methodfor
    drawing Strings on the Frame. Paint should be used
    just for Graphics
    So how do you make a component show a text? Use a Label :-)If your custom component needs to paint graphics and text then there is nothing wrong with drawing a String in the paintComponent() method. (In Swing you should override paintComponent(), not paint(). It doesn't make sense to create a JLabel with all the extra overhead that requires.
    The problem with this posting is overriding the paint(..) method of the entire frame is not a good idea.

  • On the printing slowness of Postscript produced by the JVM from calls to Graphics.drawString() (Linux/Unix)

    Happy new year,
    before the holidays my attention was drawn to an issue that supposedly the Postscript produced by the JVM is too big and hence too slow.  Here are my findings.
    The issue
    Text printing via CUPS to native Postscript printers can be slow. Printing a terms and conditions page (17000 characters/page) takes three and a half minutes to print on a Dell 2330 dn laser printer (96 MB,Max speed 33 ppm). The file is about 8 MB in size. To contrast that, rendering the text to a buffered image with 300 DPI and printing the result produces 7 MB of output which prints in 30 seconds on the same printer. More measures for different printers and documents can be found at the end of this post. The issues is registered as  "JDK-4627340 : RFE: A way to improve text printing performance for postscript devices" (http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4627340) and the proposed workaround is to use printer fonts.
    Side remark regarding the workaround
    There is a regression that prevents the workaround from working (bug 9008662 at Sun (not yet visible),  bug 8023990 at OpenJDK (https://bugs.openjdk.java.net/browse/JDK-8023990). Without knowing what other bad side effects this might have, the issue can be resolved by setting the property "sun.awt.fontconfig". On my system I set it to the location of a "fontconfig.properties" of a JVM that does not have the bug (e.g. /home/alex/openjdk_7_b147_jun_11/openjdk/build/linux-i586/bin/java -Dsun.awt.fontconfig="/etc/java-6-openjdk/fontconfig.properties" Print2DtoStream). I also successfully tested the workaround on an Oracle JVM 1.7.0_03-b04.
    Back to the main topic
    How the JVM draws text if it can't use a standard printer font
    Text is drawn with postscript path drawning commands such as "moveto", "lineto" or "curveto". As an example consider the word "ll" which looks something like this:
    %N->short for "newpath"
    N
    %paint first "l"
    %M->short for "moveto"
    0.76875 11.06 M
    %L->short for "lineto"
    0.76875 2.468 L
    1.823 2.468 L
    1.823 11.06 L
    0.76875 11.06 L
    %p->short for "closepath"
    P
    %paint second "l"
    3.649 11.06 M
    3.649 2.468 L
    4.703 2.468 L
    4.703 11.06 L
    3.649 11.06 L
    P
    The same text could be printed with a printer font using the command "(ll) show" which is much more compact but is available in Java only for the Postscript standard fonts and it isn't working at all right now as explained above.
    Is it the file size?
    My first thought was that the file size was the source of of slowness and so I wrote a small processor that would detect glyphs, normalize*1 them and place them in a dictionary. Recurring references to the same glyph were replaced by a dictionary reference  (This is incidentally the fix proposed by the original author of RFE 4627340). This shrunk the file to about 11% of the original size but the processing time surprisingly doubled.
    *1: With "normalizing" I mean applying a translation transform so that the smallest coordinates in the contours of a glyph are exactly 0. In addition I experimented with performing a normalizing scale transform so that all coordinates lie between 0 and 1 so that identical glyphs are detected at arbitrary positions and at different font sizes.
    That led to the question to why there is such a big difference in performance between a Type 1 font dictionary and a self constructed dictionary since both contain basically the same drawing instructions. The difference is apparently that fonts are cached and user drawings are not unless explicitly told.
    The Postscript "ucache" instruction
    Postscript level 2 introduces the "ucache" instruction which seems to be defined for precisely this kind of problem. From the documentation:
    "Some PostScript programs define paths that are repeated many times. To optimize the interpretation of such paths, the PostScript language provides a facility called the user path cache. This cache, analogous to the font cache, retains the results from previously interpreted user path definitions. When the PostScript interpreter encounters a user path that is already in the cache, it substitutes the cached results instead of reinterpreting the path definition. "
    After adding "ucache" instructions to my filter the speed improved by factor 10.
    To illustrate the said the "ll" text from above looked as follows after the transformation:
    %definition of the glyph "l" named "p0"
    /p0
    ucache
    0.000 0.000 1.054 8.592 setbbox
    0.000 8.592 moveto
    0.000 0.000 lineto
    1.054 0.000 lineto
    1.054 8.592 lineto
    0.000 8.592 lineto
    closepath
    } cvlit def
    G
    N
    0.769 2.468 translate
    %draw "l" at 0.769 2.468
    p0 ufill
    -0.769 -2.468 translate
    3.649 2.468 translate
    %draw "l" at 3.649 2.468
    p0 ufill
    -3.649 -2.468 translate
    For ucached shapes there is a special compact representation so that the same can be written as follows:
    /p0
    0.000 0.000 1.054 8.592
    0.000 8.592
    0.000 0.000
    1.054 0.000
    1.054 8.592
    0.000 8.592
    } cvlit def
    G
    N
    0.769 2.468 translate
    p0 ufill
    -0.769 -2.468 translate
    3.649 2.468 translate
    p0 ufill
    -3.649 -2.468 translate
    Interestingly the speed improvement remained the same on a Chinese report that had hardly any character reuse. Upon this observation I changed the filter to not use a dictionary but so simply instruct the interpreter to cache each glyph definition and the performance remained nearly the same.
    The initial "ll" text from above looks as follows after this transformation:
    N
    %paint first "l" cached
    0.76875 2.468 1.823 11.06
    0.76875 11.06
    0.76875 2.468
    1.823 2.468
    1.823 11.06
    0.76875 11.06
    } ufill
    %paint second  "l" cached
    3.649 2.468 4.703 11.06
    3.649 11.06
    3.649 2.468
    4.703 2.468
    4.703 11.06
    3.649 11.06
    } ufill
    Note that I didn't normalize the shapes.
    Why does this improve the performance so vastly if the shape is drawn only once? For a while I thought perhaps that the interpreter would consider two paths which differ only by a translation as being the same but rereading the documentation and looking at the Chinese example in which nearly all characters are unique, disproves this. The relevant part of the documentation reads:
    "Caching is based on the value of a user path object. That is, two user paths are considered the same for caching purposes if all of their corresponding elements are equal, even if the objects themselves are not.
    A user path placed in the cache need not be explicitly retained in virtual memory. An equivalent user path appearing literally later in the program can take advantage of the cached information. Of course, if it is known that a given user path will be used many times, defining it explicitly in VM avoids creating it multiple times.
    User path caching, like font caching, is effective across translations of the user coordinate system, but not across other transformations, such as scaling or rotation. In other words, multiple instances of a given user path painted at different places on the page will take advantage of the user path cache when the current transformation matrix has been altered only by translate. If the CTM has been altered by scale or rotate , the instances will be treated as if they were described by different user paths."
    An explanation that would fit the findings
    The rasterizer renders the page multiple time (perhaps in order to save memory and produce horizontal strips). On the first rendering the cache is filled and reused on the subsequent renderings thereby improving performance even if all cached items are used only once.
    Based upon this theory I hoped that the strip height would grow if I added more memory to the printer but this was not the case on the two printers for which I had memory to test with. Even substantial changes to the available memory (e.g. going from 32 MB to 96 MB) had no impact whatsoever on the performance.
    Summary
    The issue is not related to the file size as the original requester suspected but very likely due to the uncached rendering. Caching of glyphs can be achieved by using the "ucache" instruction or perhaps by placing the glyphs in font dictionaries and using the "show" operator.
    Although reported in 2003, time is apparently not healing this quick enough since printers in the 10,000$ class like the Sharp MX2310U still take a full minute to print 10 pages and a desktop printer may be blocked for over an hour for the same document.
    We will now try to use the CUPS filter and leave the printers configured as Postscript printers. If there is interest I can post the single file source of a CUPS filter that performs the inline conversion described. Apart from libl it requires no additional libraries and written using flex it is reasonably lightweight and fast.
    I would appreciate any opinion on whether or not the proposed workaround for bug 8023990 (https://bugs.openjdk.java.net/browse/JDK-8023990), namely having the system property "sun.awt.fontconfig" pointing to a working fontconfig.properties of a previously installed and working 1.6 version file, is safe.
    Measures (Appendix)
    "Terms and Conditions" report
    Testing a single page "Terms and Conditions" report in "Arial" 8pt (I am aware that "Helvetica" is width compatible and nearly looks the same but in this particular case the line height was also relevant and as explained above, printer fonts are currently not working). The page contains 17000 characters of which some parts are bold and some italic. This is a real world example and to make things worse the requirement is to print the text on the backside of every page on a certain class of reports. I am aware that this is a bit extreme but I also felt that I couldn't dismiss it as being unreasonable.
    File "Arial.ps" (7.5 MB Unmodified output of the JVM)
    Printer
    Printing time
    Dell 2330dn 32MB/96MB
    3:50 minutes
    Lexmark X658de (55 ppm, aprox. 5,000$)
      1:45 minutes
    HP LaserJet 4240n 64 MB
    1:12 minutes
    Kyocera Taskalfa 300ci (30 PPM, aprox. 8,000$)
    1 minute
    HP Color LaserJet 4650 dn 128/384MB
    51 seconds
    Sharp MX 2310U 512MB (55ppm,  aprox. 10,000$)
    31 seconds
    Arial_inline.ps (8 MB contains "ucache" without normalization and without dictionary)
    Printer
    Printing time
    32MB/96MB
    30seconds/30seconds (Improvement by factor 7.7)
    Lexmark X658de (55 ppm, aprox. 5,000$)
      15 seconds (Improvement by factor 7)
    HP LaserJet 4240n 64 MB
    47 seconds (Improvement by factor 1.5)
    Kyocera Taskalfa 300ci (30 PPM, aprox. 8,000$)
    20 seconds (Improvement by factor 5)
    HP Color LaserJet 4650 dn 128/384MB
    46 seconds (Improvement by factor 1.1)
    Sharp MX 2310U 512MB (55ppm,  aprox. 10,000$)
    14 seconds (Improvement by factor 2)
    Asian characters test
    Testing 10 pages of Asian characters in the font "WenQuanYi Zen Hei" 12pt where each page contains 49 lines by 40 unique characters. The document contains the 30,000 characters between unicode 0x4e00 and 0x9fff. This is a nonsense stress test but it illustrates  that the "ucache" speedup works even though no character is repeated in the report.
    Asian.ps  (52 MB Unmodified output of the JVM)
    Printer
    Printing time
    Dell 2330dn 32MB/96MB
    64 minutes
    Lexmark X658de (55 ppm, aprox. 5,000$)
    Not measured
    HP LaserJet 4240n 64 MB
    11 minutes
    Kyocera Taskalfa 300ci (30 PPM, aprox. 8,000$)
    Not measured
    HP Color LaserJet 4650 dn 128/384MB
    9:13 minutes
    Sharp MX 2310U 512MB (55ppm,  aprox. 10,000$)
    4:08 minutes
    Asian_inline.ps (54 MB contains "ucache" without normalization and without dictionary)
    Printer
    Printing time
    32MB/96MB
    5:30 minutes (Improvement by factor 11.6)
    Lexmark X658de (55 ppm, aprox. 5,000$)
    Not measured
    HP LaserJet 4240n 64 MB
    3:48 minutes (Improvement by factor 2.9)
    Kyocera Taskalfa 300ci (30 PPM, aprox. 8,000$)
    Not measured
    HP Color LaserJet 4650 dn 128/384MB
    2:46 minutes (Improvement by factor 3.4)
    Sharp MX 2310U 512MB (55ppm,  aprox. 10,000$)
    48 seconds (Improvement by factor 5)

    Hi Sven,
    Will putting the boilerplate in the trailer section allow me to still have it appearing on the back page of the main report? This is where it needs to be as far as the printed report goes - it is duplexed.
    Regards
    Lanny

  • How can I draw image in a vbean?

    How can I draw image in a vbean?
    this is my code :
    import java.awt.BorderLayout;
    import java.awt.Image;
    import java.awt.Graphics;
    import java.net.MalformedURLException;
    import java.net.URL;
    import com.sun.jimi.core.Jimi;
    import oracle.forms.handler.IHandler;
    import oracle.forms.properties.ID;
    import oracle.forms.ui.VBean;
    public class PrintEmailLogo extends VBean {
         URL url;
         Image img;
         boolean ImageLoaded = false;
         public void paint(Graphics g) {
              if (ImageLoaded) {
                   System.out.println("yes~~~");
                   g.drawImage(img, 0, 0, null);
              } else
                   System.out.println("no~~~");
         public boolean imageUpdate(Image img, int infoflags, int x, int y, int w,
                   int h) {
              if (infoflags == ALLBITS) {
                   System.out.println("yes");
                   ImageLoaded = true;
                   repaint();
                   return false;
              } else
                   return true;
         public void init(IHandler arg0) {
              super.init(arg0);
              try {
                   url = new URL("file:print/77G.gif");
                   img = Jimi.getImage(url);
                   Image offScreenImage = createImage(size().width, size().height);
                   Graphics offScreenGC = offScreenImage.getGraphics();
                   System.out.println(offScreenGC.drawImage(img, 0, 0, this));
              } catch (MalformedURLException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
    but when I run it in forms
    when it run Graphics offScreenGC = offScreenImage.getGraphics();
    It throw a exception:
    java.lang.NullPointerException     at com.avicit.aepcs.calendar.PrintEmailLogo.init(PrintEmailLogo.java:72)     at oracle.forms.handler.UICommon.instantiate(Unknown Source)     at oracle.forms.handler.UICommon.onCreate(Unknown Source)     at oracle.forms.handler.JavaContainer.onCreate(Unknown Source)     at oracle.forms.engine.Runform.onCreateHandler(Unknown Source)     at oracle.forms.engine.Runform.processMessage(Unknown Source)     at oracle.forms.engine.Runform.processSet(Unknown Source)     at oracle.forms.engine.Runform.onMessageReal(Unknown Source)     at oracle.forms.engine.Runform.onMessage(Unknown Source)     at oracle.forms.engine.Runform.processEventEnd(Unknown Source)     at oracle.ewt.lwAWT.LWComponent.redispatchEvent(Unknown Source)     at oracle.ewt.lwAWT.LWComponent.processEvent(Unknown Source)     at java.awt.Component.dispatchEventImpl(Unknown Source)     at java.awt.Container.dispatchEventImpl(Unknown Source)     at java.awt.Component.dispatchEvent(Unknown Source)     at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)     at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)     at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)     at java.awt.Container.dispatchEventImpl(Unknown Source)     at java.awt.Component.dispatchEvent(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)
    I change it to:
    import java.awt.BorderLayout;
    import java.awt.Image;
    import java.awt.Graphics;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.swing.JFrame;
    import com.sun.jimi.core.Jimi;
    import oracle.forms.handler.IHandler;
    import oracle.forms.properties.ID;
    import oracle.forms.ui.VBean;
    public class PrintEmailLogo extends VBean {
         URL url;
         Image img;
         public void paint(Graphics g) {
              try {
                   url = new URL("file:print/77G.gif");
                   img = Jimi.getImage(url);
                   g.drawImage(img, 0, 0, this));
              } catch (MalformedURLException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
         public void init(IHandler arg0) {
              super.init(arg0);
    But it display nothing.
    It isn't paint continuous.
    what's wrong in my vbean?
    please help me.

    The following code works fine for me:
    package oracle.forms.fd;
    import java.awt.*;
    import java.awt.event.*;
    import java.net.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import oracle.forms.handler.IHandler;
    import oracle.forms.properties.ID;
    import oracle.forms.ui.CustomEvent;
    import oracle.forms.ui.VBean;
    public class test extends VBean {
      private URL url;
      private URL m_codeBase; 
      private Image img;
    public void paint(Graphics g) {
      // draw the image
      g.drawImage(img, 0, 0, this);
    public void init(IHandler arg0) {
       super.init(arg0);
       // load image file
       img = loadImage("file:///c:/coyote.jpg");   
    public test()
        super();
       *  Load an image from JAR file, Client machine or Internet URL  *
      private Image loadImage(String imageName)
        URL imageURL = null;
        boolean loadSuccess = false;
        Image img = null ;
        //JAR
        imageURL = getClass().getResource(imageName);
        if (imageURL != null)
          try
            img = Toolkit.getDefaultToolkit().getImage(imageURL);
            loadSuccess = true;
            return img ;
          catch (Exception ilex)
            System.out.println("Error loading image from JAR: " + ilex.toString());
        else
          System.out.println("Unable to find " + imageName + " in JAR");
        //DOCBASE
        if (loadSuccess == false)
          System.out.println("Searching docbase for " + imageName);
          try
            if (imageName.toLowerCase().startsWith("http://")||imageName.toLowerCase().startsWith("https://"))
              imageURL = new URL(imageName);
            else if(imageName.toLowerCase().startsWith("file:"))
              imageURL = new URL(imageName);
            else
              imageURL = new URL(m_codeBase.getProtocol() + "://" + m_codeBase.getHost() + ":" + m_codeBase.getPort() + imageName);
            System.out.println("Constructed URL: " + imageURL.toString());
            try
              img = createImage((java.awt.image.ImageProducer) imageURL.getContent());
              loadSuccess = true;
              System.out.println("Image found: " + imageURL.toString());
              return img ;
            catch (Exception ilex)
              System.out.println("Error reading image - " + ilex.toString());
          catch (java.net.MalformedURLException urlex)
            System.out.println("Error creating URL - " + urlex.toString());
        //CODEBASE
        if (loadSuccess == false)
          System.out.println("Searching codebase for " + imageName);
          try
            imageURL = new URL(m_codeBase, imageName);
            System.out.println("Constructed URL: " + imageURL.toString());
            try
              img = createImage((java.awt.image.ImageProducer) imageURL.getContent());
              loadSuccess = true;
              System.out.println("Image found: " + imageURL.toString());
              return img ;
            catch (Exception ilex)
                    System.out.println("Error reading image - " + ilex.toString());
          catch (java.net.MalformedURLException urlex)
            System.out.println("Error creating URL - " + urlex.toString());
        if (loadSuccess == false)
          System.out.println("Error image " + imageName + " could not be located");
        return img ;
    }Francois

  • How do I paint graphics in a JFrame created by netbeans GUI builder?

    I hope it's ok to ask netbeans questions here. Frustrated with Eclipse I'm trying netbeans. I went through the tutorial for the UI builder and I have no trouble laying out the usual swing widgets like JPanels, JButtons, etc. What I haven't figured out is how to mix ordinary graphics like Graphics.draw() with these components.
    Crude example: 2 JPanels in a JFrame. The one on the left has a JSlider bar. The one on the right has a line or something that gets bigger or smaller according to the slider bar.
    If I weren't using the UI builder I'd create a new class that is an extension of JPanel, and override paintComponent() with my draw commands. If I did that to a JPanel I layed out with the UI builder it would get lumped in with the protected code that's created on the fly and probably erased.
    So how do I mix swing components with ordinary graphics without breaking the netbeans UI builder form?
    Thanks,
    Apchar

    This forum is a Java language forum. The NetBeans site has a mailing list. Nabble forums also has NB forums. The contents of both are crossposted. So, you really should post NB use questions to one of them. Post only Java language questions here.
    You can add custom code to the guarded (blue) code blocks. Open a component's property window and select the code button at the top. This allows you to insert code in numerous locations within the guarded blocks and retain the code.
    You can also click a component's property's ellipsis (...) button to bring up the Property Editor dialog box, then select "Custom Code" from the dropdown list at the top of the dialog.
    Note: the above instructions are for NB 6

  • How to call java program by HTML page

    Hi guys,
    I'm new java programer and want to build an HTML page to access to ORACLE database on NT server by JDBC, Can anyone give me a sample?
    I already know how to access database by JDBC, but I don't know how to call java program by HTML page.
    If you have small sample,pls send to me. [email protected], thanks in advance
    Jian

    This code goes with the tutorial from this web page
    http://java.sun.com/docs/books/tutorial/jdbc/basics/applet.html
    good luck.
    * This is a demonstration JDBC applet.
    * It displays some simple standard output from the Coffee database.
    import java.applet.Applet;
    import java.awt.Graphics;
    import java.util.Vector;
    import java.sql.*;
    public class OutputApplet extends Applet implements Runnable {
    private Thread worker;
    private Vector queryResults;
    private String message = "Initializing";
    public synchronized void start() {
         // Every time "start" is called we create a worker thread to
         // re-evaluate the database query.
         if (worker == null) {     
         message = "Connecting to database";
    worker = new Thread(this);
         worker.start();
    * The "run" method is called from the worker thread. Notice that
    * because this method is doing potentially slow databases accesses
    * we avoid making it a synchronized method.
    public void run() {
         String url = "jdbc:mySubprotocol:myDataSource";
         String query = "select COF_NAME, PRICE from COFFEES";
         try {
         Class.forName("myDriver.ClassName");
         } catch(Exception ex) {
         setError("Can't find Database driver class: " + ex);
         return;
         try {
         Vector results = new Vector();
         Connection con = DriverManager.getConnection(url,
                                  "myLogin", "myPassword");
         Statement stmt = con.createStatement();
         ResultSet rs = stmt.executeQuery(query);
         while (rs.next()) {
              String s = rs.getString("COF_NAME");
              float f = rs.getFloat("PRICE");
              String text = s + " " + f;
              results.addElement(text);
         stmt.close();
         con.close();
         setResults(results);
         } catch(SQLException ex) {
         setError("SQLException: " + ex);
    * The "paint" method is called by AWT when it wants us to
    * display our current state on the screen.
    public synchronized void paint(Graphics g) {
         // If there are no results available, display the current message.
         if (queryResults == null) {
         g.drawString(message, 5, 50);
         return;
         // Display the results.
         g.drawString("Prices of coffee per pound: ", 5, 10);
         int y = 30;
         java.util.Enumeration enum = queryResults.elements();
         while (enum.hasMoreElements()) {
         String text = (String)enum.nextElement();
         g.drawString(text, 5, y);
         y = y + 15;
    * This private method is used to record an error message for
    * later display.
    private synchronized void setError(String mess) {
         queryResults = null;     
         message = mess;     
         worker = null;
         // And ask AWT to repaint this applet.
         repaint();
    * This private method is used to record the results of a query, for
    * later display.
    private synchronized void setResults(Vector results) {
         queryResults = results;
         worker = null;
         // And ask AWT to repaint this applet.
         repaint();

  • How to put 2D graphics in TransformGroup?

    I can use J3DGraphics2D to draw graphics in Canvas3D, but may i put the graphics i drawed in a TransformGroup so that i can remove them later?

    I am anxious to know how to put 2D graphics in 3D TransformGroup, because
    I want to pick 2D graphics in 3D scene. For example, I drew some 2D graphics
    in 3D scene, line, sphere, rect, I may pick one using mouse. As we know, we can
    use PickMouseBehavior to pick 3D Graphics, How can I to 2D Graphics? Thanks a lot!

  • Help in drawing graphics.

    Hi friends,
    I'm newbie in drawing graphics with Java, and I need some help in a specific part of my program.
    What I want to do is to draw a waveform of a sound file. That waveform is built based on the amplitude of each sound sample. So I have a big vector full of those amplitudes. Now what I need to do is plot each point on the screen. The x coordinate of the point will be its time position in the time axis. The y coordinate of the point will be the amplitude value. Ok... Now I have a lot of doubts...
    1 - can someone give me a simple example on how to plot points in a java app? I know I have to extend a JPainel class, but I don't know much about those paint, and repaint methods. It's all weird to me. I already searched through the tutorial and the web, but I couldn't see a simple, good example. Can someone hand me this?
    2 - Once I know how to draw those graphics, I need to find a way to put a button, or anything like that, in my app, so the user can press that button to see to next part of the waveform, since the wave is BIG, and doesn't fit entirely on the screen. Is this button idea ok? Can I use some sort of SCROLL on it, would it be better?
    Well... I'm trying to learn it all. ANY help will be appreciated, ANY good link, little hint, first step, anything.
    Thanks for all, in advance.
    Leonardo
    (Brazil)

    This will lead you, in this sample you have a panel and a button,
    every click will fill a vector with random 700 points and draw them on the panel,
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    public class Wave extends Frame implements ActionListener
         WPanel   pan    = new WPanel();
         Vector   points = new Vector();
         Button   go     = new Button("Go");
         Panel    cont   = new Panel();
    public Wave()
         super();
         setBounds(6,6,700,400);     
         addWindowListener(new WindowAdapter()
        {     public void windowClosing(WindowEvent ev)
                   dispose();     
                   System.exit(0);
         add("Center",pan);
         go.addActionListener(this);
         cont.add(go);
         add("South",cont);
         setVisible(true);
    public void actionPerformed(ActionEvent a)
         points.removeAllElements();
         for (int j=0; j < 700; j++)
              int y = (int)(Math.random()*350);
              points.add(new Point(j,y+1));
         pan.draw(points);
    public class WPanel extends Panel
         Vector   points;
    public WPanel()
         setBackground(Color.pink);
    public void draw(Vector points)
         this.points = points;
         repaint();
    public void paint(Graphics g)
         super.paint(g);
         if (points == null) return;
         for (int j=1; j < points.size(); j++)
              Point p1 = (Point)points.get(j-1);
              Point p2 = (Point)points.get(j);
              g.drawLine(p1.x,p1.y,p2.x,p2.y);
    public static void main (String[] args)
         new Wave();  
    Noah

  • How to call up an executable file (eg. MSPaint) from within my java program

    How to call up an executable file (eg. MSPaint) from within my java program

    Ummm... why would you want to get MSPaint anyway? Even in the absense of real software, Java's own graphics tools are way more sophisticated - with a little time and effort, you could write a simple paint package that beat MSPaint hands down.

  • How to add custom graphical features to cursors in Waveform Graphs

    Hi all:
    I´ve starting a project in LabView, in which I need to synchronise some events with a sound track.
    To do this, I tought that LabView would be the tool of choice, but now that I´m working on it, I
    found my self faced with some serious problems.
    What I want to do, is to represent a .wav sound file in a Waveform graph, and then use the cursors
    to mark some points in the desired places where I want things to happen, but, these events are
    going to be on during some period of time.
    So, it will be natural that some consecutive events might overlap in time, and I need to have
    some control on this.
    The best solution would be to have a rectangular strip attached to the cursors, with a lenght
    representing the exact time duration of the event.
    But this is only possible on my dreams, because I dont see any tools on LabView that aloud us to implement
    any extra graphical features on the cursors.
    But as I learned more about LabView, I found that a user can program blocks of software in C, to implement
    things that LabView does´nt do by default.
    And now I´m wondering if this could be the solution for my problem.
    Is it possible to add new custom features such as the one that I need?
    If yes, how?
    I have atached an image to give a clear ideia of what I need.
    I´ll apretiate any help.
    Thanks
    Attachments:
    LV Custom.jpg ‏40 KB

    No, you can't modify the cursors with either the native or C code. But I'm wondering if you can't get what you want with an XY graph instead of a regular graph. You can have multiple separate plots and some of them can be thick horizontal lines. I've attached a file with just some constants wired to an XY graph to show what I mean. Obviously, you'd have to calculate the values for the x and y arrays in your real situation. If you have to use a regular graph to display the .wav file, you could also overlay a transparent XY Graph on top. The other possiblity is to use a picture control to display your data. There's a couple of shipping examples (i.e. Waveform and XY Plots, XY Multi Plot) that show how data can be represented and Pen Attributes and Sub setting shows how you can draw lines of different widths.
    Attachments:
    Horizontal Bars.vi ‏30 KB

  • How to call [UIView drawRect:(CGRect)rect] many times ?

    Hi guys.
    I made implementation for UIView in order to draw shapes on UIView.
    Now I need to call again draw:(CGRect) of my custom UIView.
    But I don't know to call it again.
    When call again draw:(CGRect), it would be cleared previous drawn shapes.
    How can I do it ?
    This is my code sample :
    //MyView.h
    #import <UIKit/UIKit.h>
    @interface MyView : UIView {
    NSMutableArray *lines;
    @property (nonatomic, retain) NSMutableArray *lines;
    //MyView.m
    #import "MyView.h"
    #import "MyPoint.h"
    @implementation MyView
    @synthesize lines;
    - (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
    lines = [[NSMutableArray alloc] init];
    return self;
    - (void)drawRect:(CGRect)rect {
    CGFloat red[4] = {1.0f, 0.0f, 0.0f, 1.0f};
    CGContextSetStrokeColor(c, red);
    CGContextBeginPath(c);
    int count = [lines count];
    for(int i = 0; i < count - 1; i ++) {
    MyPoint *point1 = (MyPoint*)[lines objectAtIndex:i];
    MyPoint *point2 = (MyPoint*)[lines objectAtIndex:i + 1];
    CGContextMoveToPoint(c, point1.x, point1.y);
    CGContextAddLineToPoint(c, point2.x, point2.y);
    CGContextStrokePath(c);
    I tried to call draw method in NSThread ([self performSelectorOnMainThread:@selector(startDraw) withObject:nil waitUntilDone:NO];) following as :
    - (void)startDraw {
    MyView *view = (MyView)self.view;
    [view drawRect:self.view.frame];
    In the console :
    Sun Nov 29 10:19:36 apples-imac.local MyApp[11909] <Error>: CGContextSetStrokeColor: invalid context
    Sun Nov 29 10:19:36 apples-imac.local MyApp[11909] <Error>: CGContextBeginPath: invalid context
    Sun Nov 29 10:19:36 apples-imac.local MyApp[11909] <Error>: CGContextMoveToPoint: invalid context
    Sun Nov 29 10:19:36 apples-imac.local MyApp[11909] <Error>: CGContextAddLineToPoint: invalid context
    Sun Nov 29 10:19:36 apples-imac.local MyApp[11909] <Error>: CGContextDrawPath: invalid context
    What is wrong here ?
    Thanks in advance.

    Never call drawRect from your code. When you want the entire view to be redrawn, use setNeedsDisplay. E.g.:
    // myViewController.m
    - (void)updateView:(NSData*)newData {
    // compute some new coords based on newData
    self.view.newPoint = [self computePoint:newData];
    // request redraw
    [self.view setNeedsDisplay];
    As shown in the example, you normally only need a redraw when something that affects the drawing has changed. You don't need to ask for a redraw when the view is first loaded, since the first drawing is automatic.
    Also I'm concerned about your mention of a new thread. Additional threads should be avoided if at all possible, especially if you have less than two years of experience with Cocoa. Although xnav pointed you to some good documentation in reply to your last question, you should do everything you can to get the desired results without NSThread. I promise that extra thread will be nothing but trouble for you. If you explain what you're trying to accomplish, maybe someone here can suggest an implementation that only uses the main thread, ok?
    - Ray

  • Draw graphics on Image and Save it

    hi!,
    Can anyone help me how to draw graphics(Line, rectangle.ect) on an Image and save it. I need to do the following steps.
    1. Get the Image from the local file system
    2. Based on the parameters i receive for graphics(Ex: rectangle).
    -I have to draw a rectangle on the Image.
    3. Save the Image again to the file system
    I would appreciate if any one has any ideas or sample code I can start with.
    Thanks!!!

    Here's an example using the javax.imageio package.
    import java.awt.Color;
    import java.awt.Graphics2D;
    import java.awt.Rectangle;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    public class DrawOnImage {
        public static void main(String[] args) {
            try {
                BufferedImage buffer = ImageIO.read(new File(args[0]));
                Graphics2D g2d = buffer.createGraphics();
                Rectangle rect = new Rectangle(10, 10, 100, 100);
                g2d.setPaint(Color.RED);
                g2d.draw(rect);
                ImageIO.write(buffer, "JPG", new File(args[1]));
            } catch (IOException e) {
                e.printStackTrace();
    }

  • How to call adobe's default signing dialogue after my own signature capture dialogue

    Hi,
    Working from the DocSign example I have create my own dialogue in which I can enter my signature and successfully draws the signature and signs the document (with my hardcoded sefl-signed certificate). I want to give the user the option to choose his/her own certificate or to generate a self-sign certificate (just like the adobe's default signing dialogue).
    Is there a way in which I can call the default adobe's signing dialogue right after I have called my signature dialogue? So that it still draws my signature, but uses the default siging to sign the document?
    Regards,
    Magda

    I'm confused here.
    You want Acrobat to do the actual signing BUT you want to provide the appearance for the signature field only – is that correct?
    From: Adobe Forums <[email protected]<mailto:[email protected]>>
    Reply-To: "[email protected]<mailto:[email protected]>" <[email protected]<mailto:[email protected]>>
    Date: Wed, 5 Oct 2011 06:48:00 -0700
    To: Leonard Rosenthol <[email protected]<mailto:[email protected]>>
    Subject: How to call adobe's default signing dialogue after my own signature capture dialogue
    How to call adobe's default signing dialogue after my own signature capture dialogue
    created by magdakuit<http://forums.adobe.com/people/magdakuit> in Acrobat SDK - View the full discussion<http://forums.adobe.com/message/3954927#3954927

Maybe you are looking for

  • Microphone not working correctly / Working out of nowhere / Driver issues

    Yeah I have the T61p-A24. The microphone isn't working for me. I am trying to use skype and talk to my family. I tried a few different drivers and rolling back a few times. All of a sudden yesterday I could hear myself through my speakers. I didn't h

  • Reduce render time with wizard design pattern

    I am making a long, complex interactive dynamic form. How do I make the form so that only the page/section the user is working on is visible and renders?

  • Oracle ODBC Driver unsupported?

    Hello, I was reviewing the Oracle 10g Release 2, Release Notes for hp-ux PA-RISC (64-bit) and saw this: -====================- 2 Unsupported Products The following products are not supported with Oracle Database 10g release 2 (10.2): Oracle ODBC Driv

  • Help me! How do i reboot phone after root?

    I Just rooted my phone today. I'm using an xperia mini st15i and i've used the ray-kernel for my phone since there was so seperate one for my phone. After long days i rooted my phone properly(it showed success on runme.bat) but since then i haven't b

  • CMR SIP alias via Productvity tools

    Recently added CMR and running into an issue with SIP Alias for video endpoints.  When scheduled via the Webex portal, the SIP alias is correct ([email protected]).  However when we schedule using Productivity Tools or via Jabber, it schedules the me