Incremental Painting in Swing

Hello All!
How can I achieve incremental painting in a JPanel or in general JComponents.. By "incremental painting" I mean I do not want to lose my previous drawings on the panel aka. I want to update the drawing by adding more drawings.
An example would help this is the code:
import java.awt.*;
import javax.swing.*;
public class CustomPanel extends JPanel{
public final static int CIRCLE = 1, SQUARE = 2;
private int shape;
public void paintComponent(Graphics g){
super.paintComponent(g);
if(shape == CIRCLE)
g.fillOval(50,10,60,60);
else if(shape == SQUARE)
g.fillRect(150,110,60,60);
public void draw(int s){
shape = s;
repaint();
This class is used by the following class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CustomPanelTest extends JFrame{
private JPanel buttonPanel;
private CustomPanel myPanel;
private JButton circle, square;
public CustomPanelTest()
super("Custom Panel Test");
myPanel = new CustomPanel();
myPanel.setBackground(Color.green);
square = new JButton("Square");
square.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e)
myPanel.draw(CustomPanel.SQUARE);
circle = new JButton("Circle");
circle.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e)
myPanel.draw(CustomPanel.CIRCLE);
buttonPanel = new JPanel();
buttonPanel.setLayout(new GridLayout(1,2) );
buttonPanel.add(circle);
buttonPanel.add(square);
Container c = getContentPane();
c.add(myPanel, BorderLayout.CENTER);
c.add(buttonPanel, BorderLayout.SOUTH);
setSize(300,150);
show();
public static void main ( String args[] )
CustomPanelTest app = new CustomPanelTest();
app.addWindowListener(
new WindowAdapter() {
public void windowClosing (WindowEvent e )
System.exit(0);
While executing, either a circle or square is drawn by erasing the previous drawing. What I want to achieve is for example drawing a series of circles and/or squares without losing the previous drawings.
Thank you!!!!

This will do it. I added a bufferedimage.
import java.awt.*;
import javax.swing.*;
import java.awt.image.BufferedImage;
public class CustomPanel  extends JPanel
     public final static int CIRCLE = 1, SQUARE = 2;
     private int           shape;
     private BufferedImage I = null;
     private Graphics      G;
public void paintComponent(Graphics g)
     if (I == null)
          I = new BufferedImage(getWidth(),getHeight(),BufferedImage.TYPE_INT_ARGB);     
          G = I.getGraphics();
          G.setColor(Color.white);
          G.fillRect(0,0,getWidth(),getHeight());
     super.paintComponent(g);
     G.setColor(Color.red);
     if(shape == CIRCLE) G.fillOval(50,10,60,60);
     if(shape == SQUARE) G.fillRect(150,110,60,60);
     g.drawImage(I,0,0,null);
public void draw(int s)
     shape = s;
     repaint();
}Noah

Similar Messages

  • Incremental painting

    Hi All,
    I have a question about incremental painting. I found this post very helpful: http://forum.java.sun.com/thread.jspa?forumID=57&threadID=607073
    What I'd like to do, though, is modify the code so that DrawOnImage extends JDialog and the draw() method of DrawingPanel is triggered by an event in another class, a button in JFrame for instance. Changing "extends JFrame" to "extends JPanel" is easy enough, but I'm haven't been able to figure out how to call draw() from another class. I tried adding a public method to DrawOnImage that calls the DrawingPanel draw method. I also tried making DrawingPanel a separate class (rather than an inner class) and making draw() public. In each case, I get NullPointerExecption when I try to access g2d. What am I doing wrong?
    Thanks,
    Catherine

    how to call draw() from another classYou 'another class' should instantiate a DrawingPanel and set it visible, or, your
    'another class' get a visible DrawingPanel as its constructor argument.
    If the DrawingPanel is not visible, i.e. its paintComponent() isn't called, g2d would
    be null.

  • Help Painting in Swing

    I'm new to Swing, and am having trouble painting both buttons and other graphics.
    For instance:
    package example.src;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import example.src.*;
    public class Example extends JFrame {
        public Example() {
             this.setSize(500, 500);
             this.setTitle("Example");
             addWindowListener(new WindowAdapter() {
                  public void windowClosing(WindowEvent e)
                        System.exit(0);
              Container c = this.getContentPane();
              c.add(new DrawPanel());
              c.add(new ButtonPanel());
        public static void main(String[] args) {
             JFrame Drawing_Ex = new Example();
             Drawing_Ex.setVisible(true);
    package example.src;
    import java.awt.*;
    import javax.swing.*;
    public class DrawPanel extends JPanel implements Runnable
         private boolean x = true;
         public DrawPanel() {
              Thread thread = new Thread(this);
              thread.start();
         public void run() {
             int counter = 0;
             while (true) {
                  counter++;
                  if (counter == 500) {
                       if (x) {
                            x = false;
                       else {
                            x = true;
                       counter = 0;
                  this.repaint();
                  try {
                       Thread.sleep(1);
                  catch (InterruptedException ex) {
                       System.out.println("Failed.");
        public void paintComponent(Graphics g) {
             super.paintComponent(g);
             g.setColor(Color.blue);
             if (x) {
                  g.drawString("YES", 100, 100);
             else g.drawString("NO", 100, 100);
    package example.src;
    import javax.swing.JButton;
    import javax.swing.JPanel;
    import java.awt.event.*;
    import java.awt.*;
    public class ButtonPanel extends JPanel {
    public static JButton play;
    public static JButton changeCpu;
        public ButtonPanel() {
             super();
             this.setLayout(null);
             play = new JButton("Restart");
            play.setBounds(420, 170, 80, 30);
            play.addActionListener(new ActionListener() {
                 public void actionPerformed(ActionEvent event) {
            this.add(play);
            play.setVisible(true);
            changeCpu = new JButton("Change Level");
            changeCpu.setBounds(300, 170, 120, 30);
            changeCpu.addActionListener(new ActionListener() {
                 public void actionPerformed(ActionEvent event) {
            changeCpu.setVisible(true);
            this.add(changeCpu);
    }This should have two buttons, as well as a string yes/no that switches. However, if the buttons get added last to the content pane, the string doesn't show, and if the drawing gets added last, the buttons won't show. Any help?
    (This is for a pong game - I want two buttons, one that changes the Cpu's level and another that restarts the game, and I need the player, enemy, and ball to be drawn).

    Both using and understanding layouts, is vital in the Java X-plat language. The sooner people realize that, the better off they are.
    There were other things in the code that were either questionable or could be improved, but I stuck to concentrating of the layout.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Example extends JFrame {
      public Example() {
        this.setSize(500, 500);
        this.setTitle("Example");
        addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e)
            System.exit(0);
        Container c = this.getContentPane();
        // 'when EAST meets WEST' otherwise they are
        // stacked, and only one is visible!
        c.add(new DrawPanel(), BorderLayout.WEST);
        c.add(new ButtonPanel(), BorderLayout.EAST);
        // always (validate or) pack() the main UI
        // otherwise unpredictable behaviour will be seen
        pack();
      public static void main(String[] args) {
        JFrame Drawing_Ex = new Example();
        Drawing_Ex.setVisible(true);
    class DrawPanel extends JPanel implements Runnable
      private boolean x = true;
      public DrawPanel() {
        Thread thread = new Thread(this);
        thread.start();
        // important, so the layout does not collapse the empty
        // panel to 0x0
        setPreferredSize( new Dimension(200,200) );
      public void run() {
        int counter = 0;
        while (true) {
          counter++;
          if (counter == 500) {
            if (x) {
              x = false;
            else {
              x = true;
            counter = 0;
          this.repaint();
          try {
            Thread.sleep(1);
          catch (InterruptedException ex) {
            System.out.println("Failed.");
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(Color.blue);
        if (x) {
          g.drawString("YES", 100, 100);
        else g.drawString("NO", 100, 100);
    class ButtonPanel extends JPanel {
      public static JButton play;
      public static JButton changeCpu;
      public ButtonPanel() {
        super();
        // don't do that, except in a layout manager..
        //this.setLayout(null);
        play = new JButton("Restart");
        // use a layout manager with appropriate padding,
        // or add borders to the components
        //play.setBounds(420, 170, 80, 30);
        play.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent event) {
        this.add(play);
        play.setVisible(true);
        changeCpu = new JButton("Change Level");
        changeCpu.setBounds(300, 170, 120, 30);
        changeCpu.addActionListener(new ActionListener() {
          public void actionPerformed(ActionEvent event) {
        changeCpu.setVisible(true);
        this.add(changeCpu);
    }Edited by: AndrewThompson64 on May 31, 2008 6:56 AM

  • Custom Painting in Swing Panels.

    I am trying to implement a custom painted panel on a JFrame. The panel performs custom painting in a separate thread. In additon, the frame also adds other swing panels (containing standard components) dynamically as per menu selection. I use box layout on frame to add / remove panels.
    The paint panel doesnt render properly whenever other panels are added or replaced. The paint panel is rendered only when no other are panels added to the frame.
    There is no problem however with adding / replacing components-only panels containing no custom painting.
    Please help me understand what I am missing. Any clues / suggestions most welcome
    sridhar

    Hi,
    You have problem only when adding custom painting JPanel to the same custom painting JPanel??? Are you layering your painting methods??? Like the most upper JPanel paints and then the childs??? What do you get for drawings??? Do you use invoque later method??? What is your priority on the Threads you are using???
    JRG

  • Trying Very Hard to Paint in Swing

    I'm sorry that this is such a newbie question, and yes I've been through the forums and the web and everywhere, but the problem isn't so much that I can't find answers to this question, so much as nothing I try will work. I'm just trying to paint into a JFrame in Swing, but I can't get anything to show up. I've tried using both paint(Graphics g) and paintComponent(Graphics g), but neither of those did anything. Then I tried calling super.paintComponent(g), but I got a "cannot resolve symbol" error, and I think I spelled everything correctly and imported everything, but I may be wrong. Here's my code... I hope someone can help me.
    import javax.swing.*;
    import java.io.*;
    import java.net.*;
    import java.awt.*;
    import java.awt.event.*;
    public class Board extends Thread{
        private BufferedReader readIn;
        private String readFromServer;
        private PrintWriter sendOut;
        public Board(BufferedReader in, PrintWriter out){
         readIn = in;
         sendOut = out;
        public void run() {
         JFrame board = new JFrame("Board");
         board.addWindowListener(new WindowAdapter() {
              public void windowClosing(WindowEvent e) {
                  System.exit(0);
         board.pack();
         board.setVisible(true);
         try {
         readFromServer = readIn.readLine();
            while (true) {
             if (readFromServer.length()<2) {
             readFromServer = readIn.readLine();
             if (readFromServer.startsWith("fics%") && readFromServer.length()<10) {
                  readFromServer = readIn.readLine();
              readFromServer = readIn.readLine();
                //window.append(readFromServer);
             //window.append("\n");
             readFromServer = readIn.readLine();
         catch (IOException sio) { }
        public void paintComponent(Graphics g) {
         super.paintComponent(g);
         Image image = Toolkit.getDefaultToolkit().getImage("e:\\desktop\\page02b.jpg");
         g.drawImage(image, 0, 0, null);
         g.setColor(Color.red);
         g.drawRect(0,0,100,100);
         g.setColor(Color.blue);
         g.drawRect(0,0,100,100);
        //public void update(Graphics g) {
        //paint(g);
    }

    No offense,but it looks like you have total mess in your head.
    Here is working animation application i took from book "Java Thread Programming". Maybe it will help you.
    Why you need to construct your class in a thread that IS this class still mystery to me. Don't forget that you can create a lot of other threads which will do whatever you want.
    import java.awt.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class Slide extends JComponent {
      private BufferedImage[] slide;
      private Dimension slideSize;
      private volatile int currSlide;
    private Thread interThread;
    private volatile boolean noStopRequested;
    public Slide() {
       currSlide = 0;
       slideSize = new Dimension(50, 50);
       buildSlides();
       setMinimumSize(slideSize);
       setPreferredSize(slideSize);
       setMaximumSize(slideSize);
       setSize(slideSize);
       noStopRequested = true;
      Runnable r = new Runnable() {
              public void run() {
                   try {
                        runWork();
                         }catch(Exception x) {
                          x.printStackTrace();
       interThread = new Thread(r, "Slides");
       interThread.start();
    private void buildSlides() {
             slide = new BufferedImage[20];
        Color rectColor = new Color(100, 160, 250);
        Color circleColor = new Color(250, 250, 150);
        for(int i=0; i < slide.length; i++) {
         slide[i] = new BufferedImage(
             slideSize.width,
             slideSize.height,
           BufferedImage.TYPE_INT_RGB);
       Graphics2D gg = slide.createGraphics();
    gg.setColor(rectColor);
    gg.fillRect(0, 0, slideSize.width, slideSize.height);
    gg.setColor(circleColor);
    int d = 0;
    if(i < (slide.length/2)) {
    d = 5 + (8*i);
    }else {
    d = 5 + (8*(slide.length-i));
    int inset = (slideSize.width - d)/2;
    gg.fillOval(inset, inset, d, d);
    gg.setColor(Color.black);
    gg.drawRect(
    0, 0, slideSize.width-1, slideSize.height-1);
    gg.dispose();
    public void paint(Graphics g) {
    g.drawImage(slide[currSlide], 0, 0, this);
    private void runWork() {
    while(noStopRequested) {
    try {
    Thread.sleep(100);
    currSlide =
    (currSlide +1 )%slide.length;
    repaint();
    }catch(InterruptedException x) {
    Thread.currentThread().interrupt();
    public void stopRequest() {
    noStopRequested = false;
    interThread.interrupt();
    public boolean isAlive() {
    return interThread.isAlive();
    public static void main(String[] args) {
    Slide s = new Slide();
    JPanel p = new JPanel(new FlowLayout());
    p.add(s);
    JFrame f = new JFrame("Slide Show");
    f.setContentPane(p);
    f.setSize(250, 150);
    f.setVisible(true);

  • Whyte board painting in Swing?

    Hi everyone,
    I have an application to which I'd like to attach a home made Java "whyte board". In this a user may drag his mouse to form letters, figures or whatever. I.e. I want the "whyte board JPanel" to paint out the exact movement of the mouse only when the left button of it is pressed.
    Has anyone seen this kind of application anywhere (with open source code) or do I have to develop it from scratch? If I have to, then does anyone have a good tip of where to look to find how to catch the mouses movement (when left button is pressed), cause I can't find any good sources...
    Hope you can help!
    / jez

    Thank you all for your help! And yes with the mouselistener and all, it should work, but some work must be done.
    Reply to "ashwin0007", thanx for the tip, and yes cooperation is always welcome. May E-mail is is "[email protected]" case it is not visible here. I'm getting to "work" this weekend, so we might get somewhere.
    See ya!
    / jez

  • SwingUtilities.paintComponent - problems with painting childs of components

    Maybe this question was mention already but i cant find any answer...
    Thats what could be found in API about method paintComponent in SwingUtilities:
    Paints a component c on an arbitrary graphics g in the specified rectangle, specifying the rectangle's upper left corner and size. The component is reparented to a private container (whose parent becomes p) which prevents c.validate() and c.repaint() calls from propagating up the tree. The intermediate container has no other effect.
    The component should either descend from JComponent or be another kind of lightweight component. A lightweight component is one whose "lightweight" property (returned by the Component isLightweight method) is true. If the Component is not lightweight, bad things map happen: crashes, exceptions, painting problems...
    So this method perfectly works for simple Java components like JButton / JCheckbox e.t.c.
    But there are problems with painting JScrollBar / JScrollPane (only background of this component appears).
    I tried to understand why this happens and i think the answer is that it has child components that does not draw at all using SwingUtilities.paintComponent()
    (JScrollBar got at least 2 childs - 2 buttons on its both sides for scroll)
    Only parent component appears on graphics - and thats why i see only gray background of scrollbar
    So is there any way to draw something like panel with a few components on it if i have some Graphics2D to paint on and component itself?
    Simple example with JScrollPane:
    JScrollPane pane = new JScrollPane(new JLabel("TEST"));
    pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    SwingUtilities.paintComponent(g2d, pane, new JPanel(), 0, 0, 200, 200);Edited by: mgarin on Aug 11, 2008 7:48 AM

    Well the thing you advised could work... but this wont be effective, because i call repaint of the area, where Components painted, very often..
    So it will lag like hell when i make 10-20 repaints in a second... (for e.g. when i drag anything i need mass repainting of the area)
    Isnt there any more optimal way to do painting of the sub-components?
    As i understand when any component (even complicated with childs) paints in swing - its paint method calls its child components paint() to show them... can this thing be reproduced to paint such components as JScrollPane?

  • Problem painting a JPanel

    I am making a card game for a project. The game features some human players versus some AI players. After a player makes a move, the game should take a short pause if the player was an AI player, so that the humans can see the cards played.
    Currently, the program zips by so fast after an AI move that it's not perceivable. I thought that throwing in a Thread.sleep(1000) after a call to repaint() would solve the problem. By doing this, however, I end up with a blank grey panel from the time the first AI player moves until the time it's a human's turn(at which time the executing thread dies and lets the human take over again).
    As some general information, the project is divided into a basic model/view split. A single thread of execution runs from the display to the model when a button is pressed, and the repaint is called by a callback from the model to the view. I have tried locating the sleep in different places(after the repaint, before the repaint, during AI move selection) with the same result.
    Any suggestions?

    You need to learn more about threading in swing. here is exellent chapter with example how to use timed paint in swing.
    http://developer.java.sun.com/developer/Books/javaprogramming/threads/chap9.pdf
    Here are links to articles in swing connection. You will be interested in topics about threads and using swing timer:
    http://java.sun.com/products/jfc/tsc/articles/
    It will greatly improve your app.
    Regards

  • The bane of my existance = paint()  Please help!

    I am forever getting frustrated with trying to draw things in java and even when I went through my classes in college we hit the basics but no further with this. Basically I am attempting to set up a checker board and want to draw multiple canvases in different states obviously to render a working checker board with pieces, moves etc.
    Every book and online reference that I can find has all the work done in the paint method of the canvas that is being drawn on and not from the parent(if this is even possible...is it???).
    I would like to do something like this from the parent frame:
         private void initializeBlackLayers(int initState) {
              JPanel initPanel;
              // for each state the square can be in create a panel to display that state
              for (int numState = 1; numState < 11; numState++) {
                   // create a new panel and set the size of the panel for the square
                   initPanel = new JPanel();
                   initPanel.setSize(sqSize);
                   // need to figure out which state we are creating for the square and
                   // then create that specific state for the current panel
                   switch (numState) {
                        case 1:
                             initPanel.setBackground(Color.BLACK);  // the plain black sq
                             break;
                        case 2:
                             initPanel.setBackground(Color.BLUE);  // the plain black sq selected for move
                             break;
                        case 3:
                             //NEED TO DRAW A RED CIRCLE, BLACK BACKGROUND
                             break;
                        case 4:
                             initPanel.setBackground(Color.BLUE);
                             // NEED TO DRAW A RED CIRCLE
                             break;
                        // insert code adding new panel to this layered pane and end switch, function etcI figure I either need to set up a new class for each state of the square and draw individually(which I REALLY don't want to do, read: there has GOT to be a better way) or figure out how to set the global color and just draw a filled in oval with the current color in a generic ovalCanvas for each state in the code above in the parent class. If anyone could enlighten me, I would be forever grateful for getting me out of having an extremely frustrating time with this.

    camickr wrote:Well, first of all why would people who have never written a Swing application no anything about the paint() method.Secondly, you should not be overriding the paint() method. Custom painting in Swing is done by overriding the paintComponent() method. Overriding paint() is the way it is done when using AWT.>
    Regardless, it's still the same question, whether you are using paint or paintComponent, my question is the same: How can you get a parent class to draw multiple different canvases(if using AWT) or JPanels (if swing) without constructing the individual components individually. For example, I want to have a Frame (seeing as we are not in the swing forum) that has 2 canvases one with a red circle on a black background and one with a green triangle on a blue background. Is it possible to write this from the frame, initalize 2 canvases and again from the frame, tell the canvases what you want on them?
    Start by reading the Swing tutorial on [How to Use Layered Panes|http://java.sun.com/docs/books/tutorial/uiswing/TOC.html]. The tutorial also has a section on Custom Painting.
    I did, it doesn't explain what I want to do. In their example they are just coloring the background to show up so you can see the individual panes. This is where I get stuck and what I am asking about: Write the same code they use in that example but put something on those colored backgrounds as well. Can you do it from the JLayeredPane class?

  • Background Painting of "Out of focus" tabbed Panel (JTabbedPane) ?

    Hi
    I would like to add a on going Bar Graph to a JTabbedPane, this works fine if the specific Tab is in Focus, but when the tab is switched, Painting stops!
    How can i ensure the painting continues in the background!
    Here is an example which demo's the problem! Also, watch the standard out...
    Any idea's how to solve this ?
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import javax.swing.JPanel;
    import java.util.*;
    public class TestPanel extends JPanel {
        // Define the height and width of the bars. Given by calling process.
        private int height [];
        private int width;
        // Define the starting point of the bar chart and base line.
        private int top = 5;
        private int base = 100 + top;
        private int middle = (base/2)+(top/2);
        private int baseOffset = 3;
        private int indent = 45;
        private int step = (base - top)/10;
        private int baseLen = 0;
        private int tpsArray[];
        private int maxValue;
        private int counter = 0;
        private int value;
        public TestPanel(String server, String file ) {
            tpsArray = new int[32768];
            JFrame f =  new JFrame();
            JTabbedPane t = new JTabbedPane();
            // Set the Content and Window layout
            f.setLayout( new BorderLayout() );
            t.add( panel(), "Tab A");
            t.add( new JLabel("I AM TAB B"), "Tab B");
            f.add( t, BorderLayout.CENTER);
            //f.setExtendedState( Frame.MAXIMIZED_BOTH );
            f.setSize(400,400);
            f.setVisible(true);
        public JPanel panel() {
            // Define the JPanel to hold the graphic
            JPanel panel = new JPanel( new BorderLayout());
            panel.setBackground( Color.white );
            AnnimationModel annimationModel = new AnnimationModel();
            AnimationView animationView = new AnimationView(annimationModel);
            panel.add(animationView, BorderLayout.CENTER);
            return panel;
        private class AnimationView extends JPanel {
            private Dimension d = new Dimension();
            AnimationView(AnnimationModel annimationModel) {
                // Save a reference to the model for use
                // when the view is updated
                annimationModel_ = annimationModel;
                // Listen for the events indicating that the model has changed
                annimationModel_.addObserver(new Observer() {
                    public void update(Observable o, Object arg) {
                        // All we need to do is to get the view to repaint
                        AnimationView.this.repaint();
            public void paintComponent(Graphics g) {
                super.paintComponent(g);
                Graphics2D g2d = ( Graphics2D ) g;
                baseLen = getPanelWidth() - indent * 2 ;
                System.out.println("Painting Again.... Counter = " + counter  );
                int pos = ( indent + 6 );
                addOutLine(g2d);
                // Update the view based on the information in the model.
                g.setColor(Color.green);
                for ( int i=counter;i>0;i--) {
                    if ( pos > ( baseLen + indent )  ) break;
                    g.fill3DRect( pos, (base-tpsArray), 2, tpsArray[i], true );
    pos = pos + 2;
    tpsArray[counter] = value;
    public int getPanelWidth() {
    d.width = getWidth();
    return d.width;
    public void addOutLine(Graphics2D g2d) {
    // Setup the percentage markings on left vertical bar
    g2d.setColor( Color.GRAY );
    g2d.setFont( new Font("Sanserif", Font.PLAIN, 10));
    g2d.drawString( "0", (indent - 14), base + baseOffset );
    // Display the last TPS rate
    g2d.drawString( "" + maxValue, (indent - 20 ) , top+baseOffset );
    // Display the last TPS rate
    g2d.drawString( "(" + value + ")", 3, base + baseOffset );
    // Draw vertical line from top of bar chart to base line
    g2d.drawLine( indent, top, indent, base + baseOffset );
    // Draw horizontal base line
    g2d.drawLine( indent, base, indent+baseLen, base);
    // Draw horizontal top tick mark
    g2d.drawLine( (indent)-5, top, (indent)+5, top);
    // Draw horizontal tick line at 50% or middle point
    g2d.drawLine( (indent)-5, middle, (indent)+5, middle);
    // Draw horizontal tick at bottom base line
    g2d.drawLine( (indent)-5, base, (indent)+5, base);
    // Draw the dotted lines across the bar chart.
    g2d.setColor( new Color( 160,223,233));
    float dashes[] = { 1 };
    g2d.setStroke( new BasicStroke( 1, BasicStroke.JOIN_MITER, BasicStroke.JOIN_ROUND, 0, dashes, 0));
    for (int i=base; i>=top ;i=i-step) {
    g2d.drawLine( indent + 6, i, (indent+baseLen), i );
    // The saved reference to the model
    private AnnimationModel annimationModel_;
    private class AnnimationModel extends Observable {
    // private Shared sharedRef = new Shared();
    AnnimationModel() {
    Thread annimationThread = new Thread() {
    public void run() {
    while(true) {
    try {
    Thread.sleep(1000);
    } catch ( Exception e ) {
    value = 1 + (int) (Math.random() * 100 );
    counter++;
    // Notify the observers
    setChanged();
    notifyObservers();
    annimationThread.start();
    // Simple test main
    static public void main(String[] args) {
    TestPanel app = new TestPanel(null,null);
    Thanks,
    Rob

    How can i ensure the painting continues in the background! Well, I don't think you force painting since Swing appears to be smart enough to not paint a component that isn't visible.
    However, you should be able to do your painting on an offscreen image. So your offscreen image will be continually update. Then your paintComponent(...) method simply paints this offscreen image.
    This posting should get your started using this approach:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=607073

  • Difference between paint() and paintcomponent()

    What's the difference between the paint(), paintComponent(), paintAll(), repaint() and update() methods? Which one is preferred when printing graphics with a printer?

    http://java.sun.com/docs/books/tutorial/uiswing/painting/index.html
    http://java.sun.com/docs/books/tutorial/2d/printing/
    paint          ---> AWT
    paintComponent ---> Swing
    repaint(AWT)   ---> update(background) ---> paint
    repaint(Swing) ---> in paintComponent  ---> super.paintComponent(background)

  • Applet.getImage() but so sloooooowly...

    I've seen a couple of questions posted about this issue, but no resolution. Essentially, performance of Applet().getImage() is unacceptably slow. It happens on my machine, and others.
    I'm using PlugIn 1.3.1 in WinIE 5.5, and have the following simple JApplet:
    public class GoofyApplet extends JApplet
    public void init()
    Image img = getImage(getDocumentBase(), "goofy/mickey/rtb_down.jpg"); // a 4K .jpg
    JLabel lab = new JLabel("test", new ImageIcon(img), JLabel.CENTER);
    Container content = getContentPane();
    content.add(lab);
    validate();
    repaint();
    I run that, and have ample time to curse and fume. About 20-50 seconds.
    Note the docs for getImage:
    "This method always returns immediately, whether or not the image exists. When this applet attempts to draw the image on the screen, the data will be loaded. The graphics primitives that draw the image will incrementally paint on the screen."
    First of all, timing tests have shown that this definition of "immediately" is pretty flexible. In my last test, getImage took 38230 ms.
    I've been cruising around the Forums, looking for an answer to this question and have yet to find it. This is disturbing--I can't believe SUN would ship the plug-in with this kind of behavior--but does this mean there is no solution?
    Cheers,
    Jon

    You need to wait for the image to load in an applet. If you use the Swing version of ImageIcon it will do this automatically for you. Else, use the following methods:
    * Loads an image as a resource.
    * Note:  With Swing, could use ImageIcon instead of createImage()/MediaTracker.
    public Image loadImage(String imageName) {
       Image image = null;
       URL url = getClass().getResource(imageName);
       try {
          image = createImage((ImageProducer) url.getContent());
          if (image==null) throw new Exception();
          waitForImageToLoad(this,image);
       } catch (Exception e) {
          System.out.println("unable to load image: "+imageName);
       }//end try
       return image;
    }//end loadImage
    * wait for an image to completely load. Use in an applet.
    public static void waitForImageToLoad(Component component, Image image) {
       MediaTracker tracker = new MediaTracker(component);
       try {
          tracker.addImage(image, 0);
          tracker.waitForID(0);
       } catch (InterruptedException e) {
          //this should not occur
          e.printStackTrace();
       }//end try
    }//end waitForImageToLoad

  • Image does not appear in applet.

    I am reading the book, Teach Yourself Java in 21 Days.
    There is an example in Ch.11 that shows how to load an image into the applet.
    I have tried to use the code provided as is along with an image as defined in the code. I have also uploaded the html, class and image to a folder on the web. Unfortunately, the image does not appear in the applet. The image does have an image that I created using ms paint.
    Here is the code I am currently using from the book:
    import java.awt.Graphics;
    import java.awt.Image;
    public class LadyBug2 extends java.applet.Applet {
         Image bugimg;
         public void init() {
             bugimg = getImage(getCodeBase(),
                 "ladybug.gif");
         public void paint(Graphics g) {
             int iwidth = bugimg.getWidth(this);
             int iheight = bugimg.getHeight(this);
             int xpos = 10;
             // 25 %
            g.drawImage(bugimg, xpos, 10,
                iwidth / 4, iheight / 4, this);
             // 50 %
             xpos += (iwidth / 4) + 10;
             g.drawImage(bugimg, xpos , 10,
                  iwidth / 2, iheight / 2, this);
             // 100%
             xpos += (iwidth / 2) + 10;
             g.drawImage(bugimg, xpos, 10, this);
             // 150% x, 25% y
             g.drawImage(bugimg, 10, iheight + 30,
                 (int)(iwidth * 1.5), iheight / 4, this);
    }I tried placing the image in an images folder and I also tried changing the code to getImage(getDocumentBase(), "ladybug.gif")
    as well as tried getImage(getCodeBase(), "ladybug.gif") in order to try and grab the image from the same directory as the class file and the html file.
    The image file's name is: ladybug.gif
    The code in the html file:
    <HTML>
    <HEAD>
    <TITLE>Lady Bug</TITLE>
    </HEAD>
    <BODY>
    <P>
    <APPLET CODE="LadyBug2.class" WIDTH=1024 HEIGHT=500>
    </APPLET>
    </BODY>
    </HTML>
    I have gotten previous applet examples from the book to work. One of them did have an error in the author's code which I fortunately was able to overcome. This time, I am afraid, the error eludes me.
    Thanks in advance.
    I do see that there is no start/stop/run in this version, but I believe this should still work because of the init. I am guessing that maybe the problem lies somewhere in there.
    Message was edited by:
    gnikollaj

    According to the javadoc:
    getImage
    public Image getImage(URL url,
    String name)Returns an Image object that can then be painted on the screen. The url argument must specify an absolute URL. The name argument is a specifier that is relative to the url argument.
    This method always returns immediately, whether or not the image exists. When this applet attempts to draw the image on the screen, the data will be loaded. The graphics primitives that draw the image will incrementally paint on the screen.
    Parameters:
    url - an absolute URL giving the base location of the image.
    name - the location of the image, relative to the url argument.
    Returns:
    the image at the specified URL.
    I am confused as to how to use the name after the url.
    Should it read something like:
    bugimg = getImage("http://g.jtrusty.com/JavaApplet/", "LadyBug.gif");
    EDIT: I still get the same error, cannot find symbol at getImage.
    Message was edited by:
    gnikollaj

  • Problem in drawing a line in Java Application Program

    Hi,
    I am trying to draw a line after a message is displayed on the screen. But the line is not at all coming on the screen while running. but I can see a red line is appearing on the screen first and and it is getting overridden.
    There is something wrong in the concept what I understood about graphics.Can anybody help to
    understand where the problem is ?
    Here is the part of the code which used to draw line.
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.table.*;
    import java.io.*;
    import java.sql.*;
    import java.util.*;
    import java.util.Date.*;
    import java.text.*;
    import java.lang.*;
    import MyPack.*;
    class chalan_pay extends JFrame
    JTextField jt1,jt2,jt3,jt4,jt5;
    JLabel jlh,jl1,jl2,jl3,jl4,jl5,jl10;
    JButton bt1,bt2,bt3;
    Choice ch1,ch2,ch3,ch4;
    Connection con = null;
    int i1no,i2no,i3no,i4no,itno;
    String idate;
    public chalan_pay()
    getContentPane().setLayout(null);
    jt1= new JTextField(5);
    jt1.setBounds(110,150,50,20);
    jt2= new JTextField(10);
    jt2.setBounds(400,150,100,20);
    jt3= new JTextField(3);
    jt3.setBounds(590,150,30,20);
    jt4= new JTextField(2);
    jt4.setBounds(750,150,30,20);
    jlh= new JLabel();
    jlh.setText("CHALLAN DETAILS");
    jlh.setBounds(300,50,200,20);
    jl1= new JLabel();
    jl1.setText("IGM No. ");
    jl1.setBounds(50,150,100,20);
    jl2= new JLabel();
    jl2.setText("IGM Date ");
    jl2.setBounds(340,150,100,20);
    jl3= new JLabel();
    jl3.setText("Line No. ");
    jl3.setBounds(530,150,100,20);
    jl4= new JLabel();
    jl4.setText("Subline No. ");
    jl4.setBounds(680,150,100,20);
    jl10= new JLabel();
    jl10.setBounds(100,200,300,20);
    ch1= new Choice();
    ch1.setBounds(170,150,150,20);
    getContentPane().add(ch1);
    ch1.addItemListener(new Opt1());
    bt1= new JButton("Exit");
    bt1.setBounds(200,600,100,20);
    getContentPane().add(bt1);
    bt1.addActionListener(new Ex());
    try
    con=db_connect.getConnection();
    Statement st1 = con.createStatement();
    ResultSet rs1 = st1.executeQuery("select igm_no,to_char(igm_dt,'DD-MON-YY'),line_no,subline_no from "+
    "det_item order by igm_no");
    while(rs1.next())
    ch1.addItem(String.valueOf(rs1.getInt(1))+" "+rs1.getString(2)+" "+
    String.valueOf(rs1.getInt(3))+" "+String.valueOf(rs1.getInt(4)));
    rs1.close();
    st1.close();
    catch(Exception e){e.printStackTrace();}
    getContentPane().add(jlh);
    getContentPane().add(jl1);
    getContentPane().add(jt1);
    getContentPane().add(jl2);
    getContentPane().add(jt2);
    getContentPane().add(jl3);
    getContentPane().add(jt3);
    getContentPane().add(jl4);
    getContentPane().add(jt4);
    getContentPane().add(jl10);
    setSize(900,700);
    setVisible(true);
    show();
    public void paint(Graphics g)
    g.setColor(Color.red);
    g.drawLine(0,300,600,300);
    class Ex implements ActionListener
    public void actionPerformed(ActionEvent evt)
    if(evt.getSource() == bt1)
    dispose();
    return;
    This code is incomplete. The program is compiled and Ran. I am unable to see the Line.
    Is it because , I am using contentPane ?. Please help me to cake it clear.
    mjava

    I have no idea what JTutor is, but if it tells you to override paint() in Swing, it's not worth its disk space.
    [http://java.sun.com/docs/books/tutorial/uiswing/painting/closer.html] clearly says that for all practical purposes paintComponent will be the only method that you will ever need to override.

  • Panel doesn't display properly until I resize the frame

    Hiya folks,
    I'm currently trying to write a simple piece of music notation software. This is my first time using swing beyond a relatively simple JApplet and some dialog stuff. Anywho, I ran into a pretty discouraging issue early on. So far I've got a frame with a menu bar and a toolbar on the bottom border. The toolbar contains a button which should draw a new staff panel containing 11 panels (potentially more) within it, alternating between lines and spaces. Sort of like this:
    import javax.swing.*;
    import java.awt.*;
    public class Staff extends JPanel {
       private static JPanel nsp1,nsp3,nsp5,nsp7,nsp9,nsp11;
       private static JPanel nsp2,nsp4,nsp6,nsp8,nsp10;
       private ImageIcon image= new ImageIcon(this.getClass().getResource( "icons/treble clef.gif"));
        public Staff(){
        setLayout(new GridLayout(11,1));
        add(nsp1= new NoteSpace());
        add(nsp2= new LineSpace());
        add(nsp3= new NoteSpace());
        add(nsp4= new LineSpace());
        add(nsp5= new NoteSpace());
        add(nsp6= new LineSpace());
        add(nsp7= new NoteSpace());
        add(nsp8= new LineSpace());
        add(nsp9= new NoteSpace());
        add(nsp10= new LineSpace());
        add(nsp11= new NoteSpace());
    static class NoteSpace extends JPanel{
        public NoteSpace(){
        setPreferredSize(new Dimension(this.getWidth(),2));
    static class LineSpace extends JPanel{
          public LineSpace(){
          setPreferredSize(new Dimension(this.getWidth(),1));
          public void paint(Graphics g) {
              super.paint(g);
              g.drawLine(0, (int) super.getHeight()/2, (int)super.getWidth(), (int)super.getHeight()/2);
    }Anyway, this panel displays as a tiny box wherein nothing is visible until I resize the frame. Really frustrating. And I have have no idea what the problem might be. Here's the actionlistener:
    jbtcleff.addActionListener(new ActionListener (){
            public void actionPerformed (ActionEvent e){
                staff.setBounds(50,panel.getHeight()/2,panel.getWidth()-50,panel.getHeight()/2);
                panel.add(staff);
                staff.repaint();
            });...which is located in a custom jtoolbar class within the Main class, an extension of JFrame:
    public class Main extends JFrame{
       JMenuBar jmb=new CustomMenuBar();
       JToolBar jtb= new CustomToolBars("ToolBar");
       static boolean isStaff=false;
       static boolean isNote=false;
       static JPanel panel = new JPanel();
       private static Staff staff= new Staff();
        private static Toolkit toolkit= Toolkit.getDefaultToolkit();
       private static Image image=toolkit.getImage("C:/Users/tim/Documents/NetBeansProjects/ISP/src/MusicGUI/icons/treble clef.jpg");
        private static Cursor noteCursor = toolkit.createCustomCursor(image,new Point(0,0),"Image"); 
       public Main (String m) {   
            super(m);
            setJMenuBar(jmb);    
            getContentPane().add(jtb,BorderLayout.SOUTH);       
            panel.setLayout(new CardLayout(60,60));
            getContentPane().add(panel);
    public static void main (String[]args){
            JFrame frame= new Main("Music");
            frame.setSize(800,400);
            frame.setLocationRelativeTo(null);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setVisible(true);
            frame.setIconImage(image);
           Sorry for all the code. I'm desperate.
    Thanks!

    Oh my... have you been through the Swing tutorial?
    Let's look at some of your code,
    static class NoteSpace extends JPanel{
        public NoteSpace(){
        setPreferredSize(new Dimension(this.getWidth(),2));
    static class LineSpace extends JPanel{
          public LineSpace(){
          setPreferredSize(new Dimension(this.getWidth(),1));
          public void paint(Graphics g) {
              super.paint(g);
              g.drawLine(0, (int) super.getHeight()/2, (int)super.getWidth(), (int)super.getHeight()/2);
    }Here, NoteSpace and LineSpace are being set to a preferred size of 0x2 pixels, and 0x1 pixels respectfully. If you want them at 0 width, how do you expect them to show? In particular, NoteSpace isn't doing anything special. It's just a panel. Why an inner class? Lastly you should not override paint() for SWING. That's AWT stuff. For Swing, you override paintComponent(Graphics g) .
    Then we have this
    jbtcleff.addActionListener(new ActionListener (){
            public void actionPerformed (ActionEvent e){
                staff.setBounds(50,panel.getHeight()/2,panel.getWidth()-50,panel.getHeight()/2);
                panel.add(staff);
                staff.repaint();
            });I'm not sure what the variable jbtcleff is, but it seems you are adding your Staff panel to "panel" every time a button is pressed.... why? Why not just add it once (outside the action listener) and be done with it. Your panel object has a CardLayout, so I assume you meant to create a new+ staff panel everytime a button is pressed, and then add it to the card layout panel. Even so, setBounds(...) does not seem pertinant to this goal. (In fact, in most situtations the use of setBounds(...) is the antithesis of using layout managers).
    The problem you mentioned though seems to be related to the use of a JPanel (your Staff class) that adds zero-width compontents to a grid array.

Maybe you are looking for

  • User previlege

    Hi, I granted a user read-only privilege to several tables within a database. I got the error below when log in as the user to query these tables. I do added the user under security-> users. The server principle "domain/username" is not able to acces

  • External Charger for iPod touch?

    Hi. I got a doubt. Did my old external charger (it works perfectly with my old iPod Photo) works with the new iPod Touch? I'll apreciate any answer. I didn't know if plug it or not. The charger has the same voltage (5V), so I suppose that it gona wor

  • Migration R/3 - mySAP

    Hi, I need information about migration (tools, possibilities...) SAP R/3 to mySAP. I can't found any usefully documentation about it. Did anyone know resources about documentation of migration? thanks mike

  • Lightroom 4 Unable to Open Certain Nikon D800 NEFs

    I have found support for Nikon D800 NEF files incomplete in Lightroom 4 with ACR 7.0. NEF files created by the camera in 16:9 mode using the shutter release set to take stills (setting g4) cannot be previewed or imported in LR 4. Setting g4 and the 1

  • [SOLVED]Pacstrap causing error "bad interpreter"

    Hi, I am not "extremely" new to Arch as I've installed Arch on a machine(not mine) a couple of years back. But I don't exactly remember the steps. I used Lubuntu in my machine(HP dm1z) for a long time and I can be considered as a newbie here. So I we