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.

Similar Messages

  • How can I Print a JPanel including all added Components?

    Hello dear saviours,
    I have a JPanel object which is responsible for displaying a Graph.
    I need to Print the Components of this JPanel as close to what they look like to the user as possible.
    I thought about casting the JPanel into an Image of some kind, but couldn't find anything but how to add am Image to a JPanel (God damned search engines :-).
    But wait, this gets more interesting!
    I need to have control over the scale of the Printed matterial.
    I want the option to choose between a single page and dividing the drawing the JPanel displays into Multiple-Pages.
    In both cases I need full details of all the data (Nodes, Arcs, Text describing the various Nodes and Arcs names or type, etc.).Keeping the sizes of all these components is also important (that means, I don't want the nodes to be tinny-winny and the Fonts to be twice as large as the nodes and so on...).
    Attached is the code of the PrintUtillity class I created as an API for printing the JPanel data:
    package ild;
    import java.awt.*;
    import javax.swing.*;
    import java.awt.print.*;
    /** A simple utility class that lets you very simply print
    * an arbitrary component. Just pass the component to the
    * PrintUtilities.printComponent. The component you want to
    * print doesn't need a print method and doesn't have to
    * implement any interface or do anything special at all.
    * <P>
    * If you are going to be printing many times, it is marginally more
    * efficient to first do the following:
    * <PRE>
    * PrintUtilities printHelper = new PrintUtilities(theComponent);
    * </PRE>
    * then later do printHelper.print(). But this is a very tiny
    * difference, so in most cases just do the simpler
    * PrintUtilities.printComponent(componentToBePrinted).
    * 7/99 Marty Hall, http://www.apl.jhu.edu/~hall/java/
    * May be freely used or adapted.
    public class PrintUtilities implements Printable {
    private Component componentToBePrinted;
    public PrintUtilities(Component componentToBePrinted) {
    this.componentToBePrinted = componentToBePrinted;
    public static void printComponent(Component c) {
    new PrintUtilities(c).print();
    public void print() {
    PrinterJob printJob = PrinterJob.getPrinterJob();
    printJob.setPrintable(this);
    if (printJob.printDialog())
    try {
    printJob.print();
    } catch(PrinterException pe) {
    System.out.println("Error printing: " + pe);
    public int print(Graphics g, PageFormat pageFormat, int pageIndex) {
    if (pageIndex > 0) {
    return(NO_SUCH_PAGE);
    } else {
    Graphics2D g2d = (Graphics2D)g;
    // double scale = 2;
    // g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    double scaleFactor = java.lang.Math.min((double)this.componentToBePrinted.getSize().width/(double)(pageFormat.getImageableWidth()),
    (double)this.componentToBePrinted.getSize().height/(double)(pageFormat.getImageableHeight()));
    g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
    g2d.scale(1.0/scaleFactor,1.0/scaleFactor);
    // disableDoubleBuffering(componentToBePrinted);
    componentToBePrinted.paint(g2d);
    enableDoubleBuffering(componentToBePrinted);
    return(PAGE_EXISTS);
    /** The speed and quality of printing suffers dramatically if
    * any of the containers have double buffering turned on.
    * So this turns if off globally.
    * @see enableDoubleBuffering
    public static void disableDoubleBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(false);
    /** Re-enables double buffering globally. */
    public static void enableDoubleBuffering(Component c) {
    RepaintManager currentManager = RepaintManager.currentManager(c);
    currentManager.setDoubleBufferingEnabled(true);

    That's a nice utility, but my JPanel gets truncated when printed. Is there a way to print a JPanel in full.

  • Ridiculously dumb question about drawing in JPanel

    Howdy everyone,
    I gotta really stupid question that I cant figure out the answer to. How do I draw an image to a JPanel, when my class inherits from JFrame?
    Thanks,
    Rick

    Ok,
    Problem. The image isnt showing up in the Frame I set up for it. Heres my code. Im trying to get this image to show up in a scollable window. Can anyone tell what the problem with this code is??
    JPanel imgPanel= new JPanel(){
    protected void paintComponent(Graphics g){
    super.paintComponent(g);
    g.drawImage(getToolkit().createImage(imstr),imgw,imgh,this);
    imgPanel.setVisible(true);
    this.getContentPane().setLayout(new BorderLayout());
    this.getContentPane().add(new JScrollPane(imgPanel));
    this.setVisible(true);
    Any ideas?
    Thanks
    Rick

  • Resize of Drawing in JPanel

    Hi,
    I am looking for some ideas on how to resize a drawing in JPanel.
    I wanted to increase its width and height at run time by dragging its end points (any direction).
    One more thing is how do I add text to the drawing at run time? Is this possible?
    My idea is to develop an application similar to MS-Word where we can add few drawings and add text to them.
    Any help would be great.
    Mathew

    The drawing code has to be written in ratios. Don't draw from x1, y1, to x2, y2 -- draw from (left + .3*width, top + .3 * height) to . . . Then the drag gesture should give you new width and height values, and you can just repaint().

  • 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.

  • Please help with a drawing on JPanel in a background.

    Hello everybody,
    I have already post this question in the main java forum and was adviced to place the question here. Since then, I have refactored the code. I need your opinion and advice.
    My task is to draw some objects on the JPanel or some other components and to place the names to the objects, for example squares, but later, from the thread. Because it can take some time, untill the names will be avaliable.
    So, I refactored the code I post before http://forum.java.sun.com/thread.jspa?threadID=5192586&tstart=15
    And now, it draws on layers and from thread on resize, with some imitating interval.
    Is it a good approach I use, is there a better way, to draw on JPanel, after some objects were already painted.
    Here is my sample, try to resize window:
    package test;
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Point;
    import java.awt.Rectangle;
    import java.awt.event.ComponentEvent;
    import java.awt.event.ComponentListener;
    import java.awt.geom.Rectangle2D;
    import javax.swing.JFrame;
    import javax.swing.JLayeredPane;
    import javax.swing.JPanel;
    public class Painter extends JFrame implements ComponentListener{
         private static final long serialVersionUID = 1L;
         private ThreadPainter threadPainter;
         JPanel panel = new JPanel() {
              private static final long serialVersionUID = 1L;
              @Override
              protected void paintComponent(Graphics g) {
                   super.paintComponent(g);
                   System.out.println("repaint");
                   Graphics2D g2d = (Graphics2D) g;
                   g2d.setColor(Color.gray);
                   g2d.fillRect(0, 0, 800, 600);
                   g2d.setColor(Color.white);
                   for (int i = 0; i < 6; i++) {
                        Rectangle2D rec2d = new Rectangle2D.Double(10 + i * 100,
                                  10 + i * 100, 10, 10);
                        g2d.fill(rec2d);
                        g2d.drawString("Square " + i, 10 + i * 100 + 20, 10 + i * 100);
                   // start thread to paint some changes later
                   if (threadPainter == null) {
                        threadPainter = new ThreadPainter();
                        threadPainter.start();
         JPanelTest panel1 = new JPanelTest();
         public class JPanelTest extends JPanel {
              private static final long serialVersionUID = 1L;
              private int times = 0;
              @Override
              protected void paintComponent(Graphics g) {
                   super.paintComponent(g);
                   Graphics2D g2d = (Graphics2D) g;
                   g2d.setColor(Color.red);
                   System.out.println("repaint panel test");
                        System.out.println("repaitn times");
                        g2d.drawString("Square " + times, 10 + times * 100 + 20, 10 + times * 100);
              public void repaintMethod(int times) {
                   this.times = times;
                   this.repaint(times * 100 + 20, times * 100, 300,300);
         public class ThreadPainter extends Thread {
              private boolean stop = false;
              @Override
              public void run() {
                   while (!stop) {
                        int cnt = 0;
                        for (int i = 0; i < 6; i++) {
                             System.out.println("do task");
                             panel1.repaintMethod(i);
                             // load data, do calculations
                             try {
                                  // emulate calcilation
                                  Thread.sleep(1000);
                             } catch (InterruptedException e) {
                                  e.printStackTrace();
                             if (stop) {
                                  break;
                             cnt++;
                        if (cnt == 6) {
                             stopThread();
              public void stopThread() {
                   this.stop = true;
         public Painter() {
              this.setLayout(new BorderLayout());
              JLayeredPane pane = new JLayeredPane();
              this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              this.setLocation(new Point(100, 100));
              this.setPreferredSize(new Dimension(800, 600));
              this.panel.setOpaque(false);
              this.panel1.setOpaque(false);
              pane.setOpaque(false);
              pane.add(panel, JLayeredPane.DEFAULT_LAYER);
              pane.add(panel1, new Integer(
                        JLayeredPane.DEFAULT_LAYER.intValue() + 1));
              this.add(pane, BorderLayout.CENTER);
              panel.setBounds(new Rectangle(0, 0, 800, 600));
              panel1.setBounds(new Rectangle(0, 0, 800, 600));
              this.addComponentListener(this);
         public static void main(String[] args) {
              Painter painter = new Painter();
              painter.pack();
              painter.setVisible(true);
         @Override
         public void componentHidden(ComponentEvent e) {
              // TODO Auto-generated method stub
         @Override
         public void componentMoved(ComponentEvent e) {
              // TODO Auto-generated method stub
         @Override
         public void componentResized(ComponentEvent e) {
              if (threadPainter != null) {
                   threadPainter.stopThread();
                   threadPainter = new ThreadPainter();
                   threadPainter.start();
         @Override
         public void componentShown(ComponentEvent e) {
              // TODO Auto-generated method stub
    }

    Hello camickr,
    thanks for your answers.
    It sounds like you are trying to add a component and
    descriptive text of this component to a panel. So the
    question is why are you overriding paintComponent()
    method on your main panel and why are you using a
    Thread.JLabel is not a good way I think, because of the performance. Think about 1000 labels on the panel. And the text can have different style, so drawString method is better here.
    Create a component that draws your "shape" and then
    add that component to the main panel that uses a null
    layout. That means you need to specify the bounds of
    the component. Then you can add a JLabel containing
    the releated text of the component. If you don't know
    the text then it can always be updated with the
    setText() method in the future. Also, the foreground
    can be updated as well.If it would be lable, I could update Text as us say and JLabels would be perfect. In this case, JLabels are not what I need.
    You said the names will not be available right away.
    Well then you don't start a thread to schedule the
    repainting of the names since you don't know exactly
    when the name will be available. You wait until you
    have the names and then simple use the setText()
    method.I have decided this way.
    Draw all objects on the panel in different layers, for different type of objects.
    Get names and make some calculations, for example, optimal position of the text on the panel (in Thread) and after it repaint();
    Repaint draw all objects, but now it have the names, which will be added too.
    The requirement is: thousand of objects on the panel
    Different type of ojbects should be drawn in different layers
    Names should be added to the objects and maybe some other drawings (showing state). Name and drawing can be done later, but should be added dynamically, after all calculation are done.

  • 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.

  • Drawing in JPanel within JApplet

    Hi, having problems drawing in jpanel that is within japplet.
    My code follows:
    * TestApplet.java
    * @author WhooHoo
    //<applet code="TestApplet.class" width="400" height="250"></applet>
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.awt.Graphics;
    import javax.swing.JButton;
    public class TestApplet extends javax.swing.JApplet implements ActionListener {
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel1;
    private Graphics g;
    private javax.swing.JButton btnTest;
    /** Creates new form Cafe */
    public TestApplet() {
    public void init() {
    jPanel1 = new javax.swing.JPanel();
    btnTest = new javax.swing.JButton();
    jPanel2 = new javax.swing.JPanel();
    btnTest.setText("test");
    jPanel1.add(btnTest);
    getContentPane().add(jPanel1, java.awt.BorderLayout.NORTH);
    jPanel2.setBorder(new javax.swing.border.TitledBorder("Draw"));
    getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER);
    btnTest.addActionListener(this);
    jPanel2.setOpaque(false);
    g=jPanel2.getGraphics();
    /** Invoked when an action occurs.
    public void actionPerformed(ActionEvent e) {
    if (e.getActionCommand().equalsIgnoreCase("test"))
    System.out.println("test");
    g.setColor(java.awt.Color.BLACK);
         g.drawString("testing",50,50);
         g.drawString("testing",50,100);
         g.drawString("testing",50,150);
         g.drawString("testing",50,200);
         g.drawString("testing",50,250);
    public void destroy()
    g.dispose();
    When this code is run the applet seems to run fine but when the button is pressed, nothing is drawn in jpanel. Can anyone see what the problem is and suggest a fix. I need to be able to pass graphics obj around to other methods to draw in the other methods also. Testing will not dispaly anywhere in applet or frame.
    plz email or post any suggestions.

    but if I can get this to workYou can get this to work, here is the working code:
    import java.awt.event.*;
    import java.awt.Graphics;
    import javax.swing.*;
    import java.awt.*;
    public class TestApplet extends JApplet implements ActionListener {
         private JPanel jPanel2,jPanel1;
         private javax.swing.JButton btnTest;
         String string1 = "";
         public TestApplet() {
         public void init() {
              jPanel1 = new JPanel();
              btnTest = new JButton();
              jPanel2 = new JPanel(){
                   public void paintComponent(Graphics g) {
                        g.setColor(java.awt.Color.BLACK);
                        g.drawString(string1,50,50);
                        g.drawString(string1,50,100);
                        g.drawString(string1,50,150);
                        g.drawString(string1,50,200);
                        g.drawString(string1,50,250);
              btnTest.setText("test");
              jPanel1.add(btnTest);     
              getContentPane().add(jPanel1, BorderLayout.NORTH);
              jPanel2.setBorder(new javax.swing.border.TitledBorder("Draw"));
              getContentPane().add(jPanel2, BorderLayout.CENTER);
              btnTest.addActionListener(this);
              jPanel2.setOpaque(false);
         public void actionPerformed(ActionEvent e) {
              if (e.getActionCommand().equalsIgnoreCase("test"))
                   System.out.println("test");
                   string1 = "testing";
                   jPanel2.repaint();
         public void destroy(){}
    }Unfortunately all painting to a component must happen inside the paint method. I don't know if what you ask is possible. I try to figure it out. Maybe someone else has an answer.
    Pandava

  • How to set glasspane in Jpanel?

    I want to block all mouse/key input in JPanel, so how to set glasspane in jpanel?

    A glass pane is for the entire frame, not just a JPanel.
    Read the Swing tutorial on [How to Use Root Panes|http://java.sun.com/docs/books/tutorial/uiswing/TOC.html] which has an example on using Glass Panes.

  • How to drop component on JPanel

    Hi,
    i want to drop some component on JPanel.I'm talking about drag n drop concept, but how to apply it on JPanel.
    For eg how to drag n drop an image from your tool bar to a JPanel.
    Thanks in advance.

    Hi,
    thanks for ur reply.
    But this link is not helping me much...more idea needed....actually my question is to use 'JPanel' to drop component....how to make it work?and also how to resize the component itself by streaching it's border ( something like taht )
    thanks...
    Edited by: DJgpmax on Jun 17, 2008 2:10 AM

  • 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

Maybe you are looking for

  • How can I import the photos from dvd or hard disk?

    Hi! How can I import/export my photos from dvd or hard disk??!

  • ADF - managed bean error in dynamic menu creation

    scenario: to create dynamic menu for two tabs : general.. general has a subtabmenu in form of menubar wid items: country, city,... i created dynamic menus for my application.wen i ran my page i got this error: SEVERE: Managedbean menuItem_General cou

  • Wireless/Ethernet Issue

    I have DSL, and when I plug the ethernet cable in to my macbook, I have no issues I also have a Linksys Wireless G router, I used to be able to connect to my wireless network. I left home for a month, and when I came back, it won't work Under network

  • Query running slow when using case inside when

    Hi All, I am in the process of creating a query as per the following conditions: select count(*) from Alpha A, Beta B where (case when A.col1='Pete' and substr(A.col2,1,12)=substr(B.col2,1,12) then 1 else -- for all other cases when A.col1 is not equ

  • Loin apex got error ora-01403?

    Hi guys: I installed apex 3.1.2 in oracle 9.2.0.3 ,but when i tred to login in apex/apex_admin,I got a error ORA-01403: no data found Unable to get workspace name. Return to application. I tried using other username ,all it returned the same error? I