How do I draw on a Jpanel

I've spent around 15 hours trying to work out how to draw something as simple as a line onto a JPanel!
I kind of understand about using paint, set color etc. if I was writing code in notepad I'm sure that it wouldn't be a problem but as I'm using the JDK SE form editor I'm very confused as to what should be done.
Basically i have a frame with 2 panels in gridLayout position and filled top to bottom left to right equally spaced.
I've added a button to the left panel. When this button is clicked I want to draw a line on the right panel. It's that simple! If I can do that then I can move on.
All the examples i've read don't show what to do when using the JDK SE form editor. Please can someone tell me exactly what to do...thanks

see if you can follow this
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Testing extends JFrame
  public Testing()
    setSize(400,300);
    setLocation(200,100);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    getContentPane().add(new DrawPanel());
    pack();
  public static void main(String[] args){new Testing().setVisible(true);}
class DrawPanel extends JPanel
  java.util.List points = new java.util.ArrayList();
  public DrawPanel()
    setPreferredSize(new Dimension(400,300));
    setBackground(Color.WHITE);
    addMouseListener(new MouseAdapter(){
      public void mousePressed(MouseEvent me){
        points = new java.util.ArrayList();
        points.add(me.getPoint());}});
    addMouseMotionListener(new MouseMotionListener(){
      public void mouseMoved(MouseEvent me){}
      public void mouseDragged(MouseEvent me){
        points.add(me.getPoint());
        DrawPanel.this.repaint();}});
  public void paintComponent(Graphics g)
    super.paintComponent(g);
    if(points.size() > 0)
      Point sPt = (Point)points.get(0);
      for(int x = 1, y = points.size(); x < y; x++)
        Point ePt = (Point)points.get(x);
        g.drawLine(sPt.x,sPt.y,ePt.x,ePt.y);
        sPt = ePt;
}if you want a bit of advice - dump the gui builder

Similar Messages

  • How do i draw on JPanel?

    Hi all,
    Is it possible to draw inside swing JPanel? If so, how to draw, say, a rectangle inside a JPanel? Thanks a bunch!
    mp

    JPanel, is a generic light weight component. By Default, they dont paint any thing except for the background, you can easily add borders and customise their painting.

  • 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 you draw a tie of two notes in the score editor window

    How do you draw a simple tie in the score editor window of Logic Pro 10 ; two quarter notes together, an eighth up-beat accross a bar line into the next measure etc? I can't find the answer in videos, help manual.  Please give a step by step how to do it.
    It's hard to believe that a program like Logic, that has more information than the New York Public Library, does not have a simple solution for tieing notes. Maybe Logic XI will have one, or "Logicians" can speak to Sibelius for a more "note-worthy" way to solving the problem so that the score editor can be more accessible for editing purposes for those that read and write manuscript. Lew Traver

    Hi
    Ties are generally automatically created as necessary. Simply adjust the length of the note in the Score (using DurationBars or the Inspector), or in the Piano Roll or Event list.
    CCT

  • How do I draw a circle in MUSE?

    How do I draw a circle in MUSE? Holding shift&rectangle tool (as in InDesign) isn't working.

    obcomm - Use the Rectangle tool to draw a square. Click the corner options in the Control toolbar, then increase the size until you have a circle.
    David

  • Help!How can i draw an image that do not need to be displayed?

    I want to draw an image and save it as an jpeg file.
    first I have to draw all the elements in an image object.I write a class inherit from Class Component,I want to use the method CreateImage,but I get null everytime.And i cannot use the method getGraphics of this object.Thus i can not draw the image.
    when i use an applet,it runs ok.I use panel and frame,and it fails.
    How can i draw an image without using applet,because my programme will be used on the server.
    Thank you.

    you could try this to create the hidden image
    try
              GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
              GraphicsDevice gs = ge.getDefaultScreenDevice();
              GraphicsConfiguration gc = gs.getDefaultConfiguration();
              offImage = gc.createCompatibleImage(100, 100);
              offG = offImage.getGraphics();
          catch(Exception e)
              System.out.println(e.getMessage());
          }

  • How do you draw a oval in cs6?

    How do you draw a oval in cs6?
    Thanks.
    Al

    Al-R wrote:
    Close but no cigar.  I just want to draw a one pixel oval but what I get now is a thick oval.  How do I draw a simple line?
    Al
    Wouldn't a one pixel oval be just a dot? Or are you meaning to say you want to draw an oval that has a one pixel wide edge?
    If the latter, then select the oval marque tool, draw your oval, then stroke (edit> stroke) the selection with a one pixel stroke, using the color off your choice.
    To draw a simple line:
    • use the Pencil tool, set the thickness in the options bar. Click where you want the line to start, then move your mouse to where you want the line to stop and shift-click to draw a straight line to that end point. PS will connect the two points with the line. Or you can free hand the line - just click and draw.
    • use the Path tool to draw your line, then pick your brush tool, set the pixel size, pick the color you want as your forground color, then in the Paths pallete drop down, select stroke path and pick the brush tool.
    • use the Line tool, inside the shape tool box. Lots of options, just need to experiement.

  • How to get BufferedImage of a JPanel

    Can anyone tell me : how to get BufferedImage of a JPanel

    I've done something like this:
    import java.awt.Graphics;
    import java.awt.LayoutManager;
    import java.awt.Dimension;
    import java.awt.image.BufferedImage;
    import java.io.InputStream;
    import java.io.FileInputStream;
    import javax.swing.JPanel;
    import com.sun.image.codec.jpeg.JPEGCodec;
    import com.sun.image.codec.jpeg.JPEGImageDecoder;
    * @author Martin Breton
    public class JBackgroundImagePanel extends JPanel {
         private BufferedImage mImage = null;
         private InputStream mImageStream = null;
         public  String mImageFilename = null;
         public JBackgroundImagePanel( String ImageFilename ) {
              super();
              mImageFilename = ImageFilename;
              initialize();
         public JBackgroundImagePanel( BufferedImage ImageFilename ) {
              super();
              mImage = ImageFilename;
              initialize();
         public JBackgroundImagePanel( InputStream ImageStream ) {
              super();
              mImageStream= ImageStream;
              initialize();
         private  void initialize() {
              if(mImage == null)
                   try {
                        ClassLoader Loader = this.getClass().getClassLoader();
                        if( mImageStream == null )
                             mImageStream = Loader.getResourceAsStream(mImageFilename);
                             if( mImageStream == null )
                                 mImageStream = new FileInputStream( mImageFilename );     
                        JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder( mImageStream );
                        mImage = decoder.decodeAsBufferedImage();
                        mImageStream.close();
                   catch(Exception e){
                        System.out.print("Image could not be loaded in JBackgroundImagePanel.");
              this.setSize(mImage.getWidth(),mImage.getHeight());
         public void paintComponent(Graphics g) {
              super.paintComponent(g);
              g.drawImage(mImage, 0, 0, null);
    }Hope this helps.
    proxi

  • How to use Draw documnet wizar to a  user form?

    Hi all,
             I  have created one form with matrix.I want to get a  copy of sales quotation's data in my form. How to get through coding.
    (How to use Draw document wizard through coding)
             My form using UDO.Just like In my form i have created one button .If i click that button the list of sales quotations for the particular cutomer has to be displayed.
              From that i have to select one quotation,that data has to be filled   in my form.
             Please help me.How to do that?
            What is the menu ID for Draw document wizard.If i get that how can i link it with the my form having datas using UDO.
             Please help me to solve this problem
    Regards
    V.Rangarajan

    Hi,
    If you want to search for a specific menu ID you only have to activate the "System Information" with the B1 menu View -> System Information. After that when you use the Menus in the top of B1 application (all menus included the same ones as in the Modules form) you will be able to ee the MenuIDs in the bottom of B1 application.
    If you want to open a document form with information inside it I will say to better create a grid with the list of documents you want to show everytime (please have a look to UI API Grid item in help file, there is also a sample in the SDK UI samples) and make one of the columns a LinkButton, when the user will click in the link button the document form will open automatically. You have also many posts talking about how to create a link button in a grid, please use the search capabitility of this forum.
    Hope it helps
    Trinidad.

  • How create new draw layer in Spreadsheet View Multisim Symbol Editor ?

    Hello,
    I would like to know how create new draw layer in Spreadsheet View Multisim Symbol Editor ?
    I am interested in this to create a contact or switch with 3 positions (one in and three out).
    So ... ??
    Best regards

    Hi,
    I am not really sure what you are trying to do with a new layer but the spreadsheet was hard coded and you cannot add a new layer.  In the Symbol Editor, there is a rectangle with dash lines, this is the symbol boundary and you can select Edit>>Resize Boundary Box to make the boundary larger/smaller.  Whatever you draw must be inside the boundary, you can only place pins outside the boundary.  The switch you created will not toggle in simulation, only the switches in the Master database can do this, R&D have to program them to toggle.
    Tien P.
    National Instruments

  • How do you draw a road?

    How do you draw a road?
    Looking to draw a road as part
    of a header for a courier website.
    I am using pse 9

    There's something at the bottom of your post, but it does not open.
    Be that as it may, this program is not well suited to drawing.
    You can draw a road scene yourself, if you wish, then scan it, and work further on the scan in PSE.
    You could photograph a road scene, use it for your header with added text.
    If you need help, post it here on the forum page (you can't do it via e-mail), and I'm sure you will receive further input.

  • I am missing some appleworks abilities I do not find on pages.  How does one "draw" vertical lines in a word processing document?

    How do I "draw" a vertical line on PAGES word processing document?

    Why not ask in the Pages forum.
    Update

  • How can I draw two differenct plots at the same graph?

    [I am beginner]
    I have two different set of data which have differenct x-axis values. How can I draw two data at the same plot?
    For example, one data set is
    x y
    1 3.5
    3 2.3
    5 1.3
    8 3.2
    The other
    1 2.3
    2.5 5.4
    4 2.5
    If I use m_graph.plotXvsY two times. But it draw only one graph at the same time.
    Please let me know. Thank you in advance.

    Do you really need the two sets of data on the same plot or is what you really care about is that the two sets of data are in the same graph? If it's the former, then there's not much that you can do since a plot can only contain one set of data. You can append to an existing set of data by calling the corresponding Chart (for example, ChartXvsY) method, but the result is that the plot's data will appear continuous.
    If it's the latter, the way to do this is to add multiple plots to the graph and plot each set of data in a separate plot. For example, go to the Plots tab in the graph's property pages, add another plot, then here's some sample code that demonstrates how to plot the sets of data from your example above:
    double xData1[] = { 1, 3, 5, 8 };
    double yData1[] = { 3.5, 2.3, 1.3, 3.2 };
    CNiReal64Vector xDataSet1(4, xData1), yDataSet1(4, yData1);
    m_graph.Plots.Item(1).PlotXvsY(xDataSet1, yDataSet1);
    double xData2[] = { 1, 2.5, 4 };
    double yData2[] = { 2.3, 5.4, 2.5 };
    CNiReal64Vector xDataSet2(3, xData2), yDataSet2(3, yData2);
    m_graph.Plots.Item(2).PlotXvsY(xDataSet2, yDataSet2);
    Hope this helps.
    - Elton

  • How can I draw a line in Preview without the arrow head

    Hello all!
    How can I draw a line in Preview without the arrow head at the end of the line?

    Yes. Once you select the line bar a new entry will appear where you can select what type of line. Based on my experience whether or not it will change is iffy.

  • How can we draw Round Rectangle Border

    how can we draw Round Rectangle Border for example, just like XP's Task Manager( under "performance tab" )

    HI,
    Check MacTopia's support area for Word. http://www.microsoft.com/mac/help.mspx?product=Word&app=4
    I would think you need graphics software for that....
    Carolyn

Maybe you are looking for

  • Free Goods Determination - Exclusive

    Hi All, Am trying to enable Free Goods determination (exclusive). I have set up the free goods determination procedure and the condition record. However, when I create my sales Order for the original material, a new line is generated with the materia

  • RegisterSchema or XML document problem

    Hi, I would like to import some XML documents from internet. The root element in document looks like that: <Report xmlns:p1="http://www.w3.org/2001/XMLSchema-instance" xmlns="spds.ifr.009.PL" p1:schemaLocation="spds.ifr.009.PL http://inetsqlcg:82/Rep

  • Please contact iTunes support to complete this trancection

    i cannot buy pokerist chips i see massage please contact iTunes support complet this trancection why?and tell me how to fit

  • Wind tunnel speed adjustment

    Hello, I am currently writing a program to adjust the speed of a wind tunnel.  I have a few questions about my program and why it is working in a particular way.  In addition,  I am fairly new to LabVIEW so if someone see's a better way of constructi

  • Searching exact match.

    Hello all, How to perform exact match using CONTAINS? For Eg. to fetch all rows having some exact text like "2003 and 2006" how to do with Contains? I know we can do this with Like operator (Like '%2003 and 2006%') but how to do it with Contains oper