ScrollPane Canvas repaint

hello everybody,
I am adding a Canvas to a ScrollPane and adding different Strings to this Canvas using drawString method.
But the problem is that when i scroll up or sidewards then the contens are repainted and i can see the contents of the Canvas. How to do this.
Pls help me out.
I am putting down my code below.
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.applet.*;
public class MyTest extends Applet
MyScroll sc;
MyNewComponent newComponent;
public void init()
sc = new MyScroll();
newComponent = new MyNewComponent();
newComponent.setBounds(0,0,100,100);
newComponent.addElements();
sc.add(newComponent);
          sc.updateComponent(newComponent);
add(sc);
          sc.validate();
class MyNewComponent extends Canvas
Vector lines,fonts,colors;
int x=0,y=10;
Enumeration linesEnu,colorEnu;
public void MyComponent()
public void addElements()
lines = new Vector();
          fonts = new Vector();
colors = new Vector();
lines.addElement(" Jogi ");
lines.addElement(" Prabha ");
lines.addElement(" Kothi ");
lines.addElement(" Naresh ");
          lines.addElement(" Murthy");
          lines.addElement(" vishal ");
linesEnu = lines.elements();
               colorEnu = colors.elements();
public void paint(Graphics g)
Font f = new Font("SansSerif",Font.BOLD,10);
while(linesEnu.hasMoreElements())
g.setColor(Color.black);
g.setFont(f);
g.drawString(""+linesEnu.nextElement(),x,y );
y=y+10;
public void update(Graphics g)
          paint(g);
class MyScroll extends ScrollPane
     public void MyScroll()
     public void paint(Graphics g)
     public void update(Graphics g)
     public void updateComponent(MyNewComponent o)
          o.repaint();
Thanks in advance

In addition to the previous reply:
You use an enumeration to go through the strings, which you create outside the paint method. As an enumeration only allows you to go through its contents once, the first call to paint after adding a string will work ok, whereas all subsequent calls will find an empty enumeration, i.e. one, where hasMoreElements returns false immediately.
So, move your inesEnu = lines.elements() command to the paint-method, too.
Bye, Marc.

Similar Messages

  • Netbeans 6.1m canvas repaint

    Hi there.
    Don't know why but have no luck with repaint.
    i have
    layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addGap(19, 19, 19)
                    .addComponent(canvas, javax.swing.GroupLayout.DEFAULT_SIZE, 306, Short.MAX_VALUE)and try to paint an image on this canvas. this.width = w;
            this.height = h;
            this.pixels = new int[pxs.length];
            for (int ii = 0; ii < pxs.length; ii++) {
                this.pixels[ii] = pxs[ii];
            this.updateImg();
        private void updateImg() {
            img = createImage(new MemoryImageSource(width, height, this.pixels, 0, width));However no luck with it
    Maybe you have a simple example?
    (full code is here mif.vu.lt/~sasa3871/Stone.zip
    Maybe someone else has some kind of an example where a user can just give coordinates where to paint things.
    In my case i need to have the posibility to read information by pixels.
    Edited by: isolated on Oct 6, 2008 10:29 AM
    Edited by: isolated on Oct 6, 2008 11:29 AM

    The code is provided here too:
    [http://pastebin.com/m5b9b16fa] - program part that extends canvas and generates image
    [http://pastebin.com/m203b0295] - part where we should load image.
    As i mentioned before this problem can be caused by the netbeans, so if anybody uses netbeans try the whole project,
    it will be more informative.
    Edited by: isolated on Oct 6, 2008 10:34 PM

  • J2ME - Canvas - repaint

    Hi,
    I have a stupid question. As far as I know the Canvas class of J2ME doesn't have getGraphics() method. That means, that I can't get the graphic representation of the Canvas object and so I can't make changes calling the properly methods of the Graphics class.
    However, the repaint() method is the only way, to do this?
    Say, I want to draw a string to the screen when the user hits a button.
    How can I do this?
    Thanks in advance,
    holex

    Hi!! I�ve a little problem, when i used repaint() method, the canvas don�t clear.
    int k=0;
    protected void pointerPressed( int x, int y){
    if (((x>0) && (x<5)) && ((y>0)&& (y<5))){
    k=1;
    repaint();
    protected void paint(Graphics g) {
    if (k==0) {
    g.drawRect(0,0,5,5);
    if (k==1) {
    g.drawRect(1,10,10,10);
    For example, when k=0 the canvas draw a rectangle, and when k=1 the canvas draw another rectangle, but i want to erase first rectangle and it�s not occur when i used repaint() method. Please, what i need to do ?

  • ScrollPane Canvas

    HI guys !
    I am making a chat window like in a instant messenger.
    I am extending a scrollpane and adding a canvas and painting strings and emoticons to this ...
    The size of the canvas is always equivalent to the size of its parent i.e the scrollpane.But wht i want is as soon as the typed messages painted on the canvas ,go beyond the height of the canvas ,the scrollbars should appear like in normal messengers and the canvas height should increase.Whenever the scrollpane's size changes ,the canvas size changes.To get the scrollbars manually i have to use the setsize.If i use the setsize method then it is called twice one by the scrollpane and one by my code- and it goes in some infinite loop.Anybody knows how to deal with this problem.. I tried to override the setsize method but eventually i had to use the setsize mehtod to change the size of the canvas which results in the same behaviour.
    Any help will be appreciated.
    Thnx,
    Viral.

    1. First option is to use a TextArea instead of a canvas, this will set the scrollbars automaticaly.
    2. If you realy need a canvas, set it size outside of paint methode, the loop you describe is probably because you set the size in the paint method.
    Noah

  • Canvas repainting in web migration

    HI,
    We are attempting to migrate our forms to the web. In several cases, we experience intermittent screen re-paints. I have made sure that we have Visible=NO and Raise on entry = yes specified for all but the first canvas. (All of these forms have multiple canvases - some as many as 20 canvases per form!)
    In one particular case, I press a button to launch a LOV, then press a button to close the LOV. Sometimes the repaints happen before the LOV is displayed, other times, the repaints occur after closing.
    This is a frustrating issue - if it was consistent, it would be much easier to fix!
    Any ideas?
    tia,
    r.b.

    A number of flicker issues have been addressed in forms patchsets. Worth noting that some JVMs exhibit flickering problems more than others. These problems can often be
    difficult to reproduce so it would be helpful to know what version of forms and the JVM you are using. If you find that it works in one patchset but not another that would also be useful to know. Ultimately you need to log a testcase with support so that the problem can be investigated.
    I know that we are already investigating some (at least on the surface) issues which sound similar.
    Regards
    Grant Ronald
    Forms Product Managemen

  • Problem about canvas repaint!

    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.util.*;
    import java.io.*;
    class DrawPie extends Canvas{
    Container cont;
    public DrawPie(Container parent){
    cont=parent;
    public void addinContainer(){
    this.setSize(200,200);
    cont.add(this,BorderLayout.SOUTH);
    public void paint(Graphics g){
    g.drawString("This is test",20,20);
    public class WelFrame extends JFrame {
    JPanel contentPane;
    BorderLayout borderLayout1 = new BorderLayout();
    // Construct the frame
    public WelFrame() {
    enableEvents(AWTEvent.WINDOW_EVENT_MASK);
    try {
    jbInit();
    catch (Exception e) {
    e.printStackTrace();
    // Component initialization
    private void jbInit() throws Exception {
    Button btn=new Button("Open");
    contentPane = (JPanel) this.getContentPane();
    contentPane.setLayout(borderLayout1);
    btn.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(ActionEvent e) {
    btn_actionPerformed(e);
    contentPane.add(btn,BorderLayout.NORTH);
    this.setTitle("Welcome to JBuilder");
    this.setSize(new Dimension(400, 300));
    //Overridden so we can exit when window is closed
    protected void processWindowEvent(WindowEvent e) {
    super.processWindowEvent(e);
    if (e.getID() == WindowEvent.WINDOW_CLOSING) {
    System.exit(0);
    //File | Exit action performed
    public void jMenuFileExit_actionPerformed(ActionEvent e) {
    System.exit(0);
    void btn_actionPerformed(ActionEvent e) {
    DrawPie dp=new DrawPie(contentPane);
    dp.addinContainer();
    public static void main(String[] args){
    WelFrame wf=new WelFrame();
    wf.show();
    I can't get the text painted when click the button open.But when i resize the Frame,the text appeared.
    how can i get the text painted when i click the button open.Thanks a lot.

    When you add a component to another component, call it the parent component, AFTER YOU HAVE CONSTRUCTED THE PARENT COMPONENT, you need to call the method validate()on the parent component to insure that this component, the parent component, has a valid layout. In your code, you're adding your component which extends Canvas to the parent component which extends JFrame AFTER instanciating it. Hence, you need to call validate() on this parent right after adding the child component. In other words, your method btn_actionPerformed should look like the following:
    void btn_actionPerformed(ActionEvent e) {
    DrawPie dp=new DrawPie(contentPane);
    dp.addinContainer();
    validate(); //or this.validate();
    calling validate() will insure re-arrenging all children correctly according to the parent layout. When you resize your form, validate is called automatically and that's why the child component shows up.
    Without calling validate(), your newly added child component is not resized and located according to the parent layout. it's probably with the size 0,0 and that's why you're not seeing the text.
    I hope I explained it clearly enough

  • Repainting a custom canvas

    I have sub-classed java.awt.Canvas to make my own Progress Bar looking component.
    Then I place that in a java.awt.Dialog, when the user clicks the java.awt.Button, the progress bar should repaint() itself to fill the bar up to the point of it's progress all of which is done by calling a custom method that moves the progress value by 1 and calls repaint() inside a for-loop.
    It works fine except for it does not repaint until the for-loop is done, but I do call inside the loop the canvas' repaint() method, as well as the custom progress() method which itself calls repaint().
    I have a loop that makes two (2) calls to method repaint() of class Canvas, but the Canvas does not repaint() until the end of the loop.

    placing repaint inside a for loop will NOT do what you want it to.
    I will have to go into a little more depth to explain why....
    when repaint is called, it does not cause an immediate repaint - instead - it posts a repaint request in the event queue. The event queue will not be serviced until your for loop has completed, so none of the repaints will be performed until the end of the loop.
    What you need to do, is create a seperate Thread, that calls repaint, and then sleeps for a set period (something like 100ms) while your updating thread is sleeping, the repaint event you have requested(by calling repaint()) will be processed, and you will see the progressbar update.
    rob,
    p.s.
    another, slightly less important problem is that multiple identical paint events in the event queue will be coalesced (merged) into a single repaint. For normal operation this is a desirable feature however, if you ever write a game in java, you will discover this may cause problems.

  • Event handling in scrollpane and graphics programming concept

    I am still unclear about what to do to refresh a canvas inside a scrollpane?
    what should i do with "repaint()" method of scrollpane??
    clearly i have to update the drawing on the graphics g of the canvas, according to the viewport of the scrollpane so that a min. area is painted only.
    will the "repaint()" method of canvas automatically get called when scrollbar is scrolled?? i tested but seems not.
    do i have to consume adjustmentevent?? seems it's not a low level event
    i saw in the console that the "update()" of the canvas sometimes get called twice when i scroll the scrollbar.
    the problem i am having is : i got different effect when i clicked on different part of the scrollbar
    clicked on the "bubble" will scroll the canvas, but once stopped the canvas that becomes visible(blank be4) is not updated
    only clicking on the area next to the "bubble" will lead to a "great leap" and the screen get updated
    i dont know how to override the adjustmentvaluechanged() actually

    i clearrect() and drawline(), filloval() in the update() of canvas and call update() inside the paint() of the canvas, i dont know if i should make it this way
    should i call repaint() of the scrollpane or repaint() of the canvas inside the adjustmentvaluechanged() of the scrollpane??

  • Problems with ScrollPane's

    I have a ScrollPane
    // Canvas
    Canvas m_MapCanvas = new Canvas();
    // ScrollPane
    ScrollPane scrollPane1 = new ScrollPane(ScrollPane.SCROLLBARS_ALWAYS);
    // add mouse listener's
    addMouseMotionListener(this);
    addMouseListener(this);
    // Canvas init
    m_MapCanvas.setBounds(0,0,512,512);
    // Init
    scrollPane1.setBounds(new Rectangle(MapPos.x, MapPos.y, 800, 600));
    scrollPane1.getVAdjustable().setUnitIncrement( 32 );
    scrollPane1.add(m_MapCanvas);
    scrollPane1.addMouseListener(this);
    scrollPane1.addMouseMotionListener(this);
    // Add
    contentPane.add(scrollPane1);Case 1:
    I load an image file into a BufferedImage. After the file is loaded I set the size if the Canvas to the size of the BufferedImage, and draw this on m_MapCanvas. The m_Canvas still remains the same size in scrollPane1.
    I set the size like this:
    m_MapCanvas.setSize(l_iWidth, l_iHeight);Case 2:
    I cant read the mouse position when the mouse is above the scrollPane
    I get the mouse envent like this:
    public void mouseMoved(MouseEvent e)
        mouseXpos = e.getX();
        mouseYpos = e.getY();
    }

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.BufferedImage;
    import java.io.*;
    import java.net.*;
    import javax.imageio.ImageIO;
    public class ScrollPaneTest
        ScrollableCanvas scrollableCanvas;
        public ScrollPaneTest()
            scrollableCanvas = new ScrollableCanvas(getImages());
            ScrollPane scrollPane = new ScrollPane();
            scrollPane.add(scrollableCanvas);
            Frame f = new Frame();
            f.addWindowListener(new WindowAdapter()
                public void windowClosing(WindowEvent e)
                    System.exit(0);
            f.add(getImageController(), "North");
            f.add(scrollPane);
            f.add(getSizeController(), "South");
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
        private BufferedImage[] getImages()
            String[] fileNames = {
                "barnowl.jpg", "timberwolf.jpg", "owls.jpg", "coyote.jpg"
            BufferedImage[] images = new BufferedImage[fileNames.length];
            for(int j = 0; j < images.length; j++)
                try
                    URL url = getClass().getResource("images/" + fileNames[j]);
                    images[j] = ImageIO.read(url);
                catch(MalformedURLException mue)
                    System.err.println("url" + mue.getMessage());
                catch(IOException ioe)
                    System.err.println("read: " + ioe.getMessage());
            return images;
        private Panel getImageController()
            Button next = new Button("next image");
            next.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent e)
                    scrollableCanvas.moveAhead();
            Panel panel = new Panel();
            panel.add(next);
            return panel;
        private Panel getSizeController()
            final Button
                less = new Button("smaller canvas"),
                more = new Button("bigger canvas");
            ActionListener l = new ActionListener()
                int direction;
                public void actionPerformed(ActionEvent e)
                    Button button = (Button)e.getSource();
                    if(button == less)
                        direction = -1;
                    if(button == more)
                        direction = 1;
                    scrollableCanvas.changeSize(direction);
            less.addActionListener(l);
            more.addActionListener(l);
            Panel panel = new Panel();
            panel.add(less);
            panel.add(more);
            return panel;
        public static void main(String[] args)
            new ScrollPaneTest();
    class ScrollableCanvas extends Canvas
        BufferedImage[] images;
        int index;
        Dimension size;
        public ScrollableCanvas(BufferedImage[] images)
            this.images = images;
            index = 0;
            size = new Dimension(images[index].getWidth(), images[index].getHeight());
        public void paint(Graphics g)
            super.paint(g);
            int w = getWidth();
            int h = getHeight();
            int imageWidth = images[index].getWidth();
            int imageHeight = images[index].getHeight();
            int x = (w - imageWidth)/2;
            int y = (h - imageHeight)/2;
            g.drawImage(images[index], x, y, this);
        public Dimension getPreferredSize()
            return size;
        public void moveAhead()
            index = (index + 1) % images.length;
            size.width  = images[index].getWidth();
            size.height = images[index].getHeight();
            invalidate();             // mark this (Canvas) invalid
            getParent().validate();   // ask scrollPane to validate its child
            repaint();
        public void changeSize(int direction)
            size.width  = size.width  + (int)(direction * 0.1 * size.width);
            size.height = size.height + (int)(direction * 0.1 * size.height);
            invalidate();
            getParent().validate();
    }

  • How to repaint a JPanel in bouncing balls game?

    I want to repaint the canvas panel in this bouncing balls game, but i do something wrong i don't know what, and the JPanel doesn't repaint?
    The first class defines a BALL as a THREAD
    If anyone knows how to correct the code please to write....
    package fuck;
    //THE FIRST CLASS
    class CollideBall extends Thread{
        int width, height;
        public static final int diameter=15;
        //coordinates and value of increment
        double x, y, xinc, yinc, coll_x, coll_y;
        boolean collide;
        Color color;
        Rectangle r;
        bold BouncingBalls balls; //A REFERENCE TO SECOND CLASS
        //the constructor
        public CollideBall(int w, int h, int x, int y, double xinc, double yinc, Color c, BouncingBalls balls) {
            width=w;
            height=h;
            this.x=x;
            this.y=y;
            this.xinc=xinc;
            this.yinc=yinc;
            this.balls=balls;
            color=c;
            r=new Rectangle(150,80,130,90);
        public double getCenterX() {return x+diameter/2;}
        public double getCenterY() {return y+diameter/2;}
        public void move() {
            if (collide) {
            x+=xinc;
            y+=yinc;
            //when the ball bumps against a boundary, it bounces off
            //bounce off the obstacle
        public void hit(CollideBall b) {
            if(!collide) {
                coll_x=b.getCenterX();
                coll_y=b.getCenterY();
                collide=true;
        public void paint(Graphics gr) {
            Graphics g = gr;
            g.setColor(color);
            //the coordinates in fillOval have to be int, so we cast
            //explicitly from double to int
            g.fillOval((int)x,(int)y,diameter,diameter);
            g.setColor(Color.white);
            g.drawArc((int)x,(int)y,diameter,diameter,45,180);
            g.setColor(Color.darkGray);
            g.drawArc((int)x,(int)y,diameter,diameter,225,180);
            g.dispose(); ////////
        ///// Here is the buggy code/////
        public void run() {
            while(true) {
                try {Thread.sleep(15);} catch (Exception e) { }
                synchronized(balls)
                    move();
                    balls.repairCollisions(this);
                paint(balls.gBuffer);
                balls.canvas.repaint();
    //THE SECOND CLASS
    public class BouncingBalls extends JFrame{
        public Graphics gBuffer;
        public BufferedImage buffer;
        private Obstacle o;
        private List<CollideBall> balls=new ArrayList();
        private static final int SPEED_MIN = 0;
        private static final int SPEED_MAX = 15;
        private static final int SPEED_INIT = 3;
        private static final int INIT_X = 30;
        private static final int INIT_Y = 30;
        private JSlider slider;
        private ChangeListener listener;
        private MouseListener mlistener;
        private int speedToSet = SPEED_INIT;
        public JPanel canvas;
        private JPanel p;
        public BouncingBalls() {
            super("fuck");
            setSize(800, 600);
            p = new JPanel();
            Container contentPane = getContentPane();
            final BouncingBalls xxxx=this;
            o=new Obstacle(150,80,130,90);
            buffer=new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_RGB);
            gBuffer=buffer.getGraphics();
            //JPanel canvas start
            final JPanel canvas = new JPanel() {
                final int w=getSize().width-5;
                final int h=getSize().height-5;
                @Override
                public void update(Graphics g)
                   paintComponent(g);
                @Override
                public void paintComponent(Graphics g) {
                    super.paintComponent(g);
                    gBuffer.setColor(Color.ORANGE);
                    gBuffer.fillRect(0,0,getSize().width,getSize().height);
                    gBuffer.draw3DRect(5,5,getSize().width-10,getSize().height-10,false);
                    //paint the obstacle rectangle
                    o.paint(gBuffer);
                    g.drawImage(buffer,0,0, null);
                    //gBuffer.dispose();
            };//JPanel canvas end
            addWindowListener(new WindowAdapter() {
                @Override
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            addButton(p, "Start", new ActionListener() {
                public void actionPerformed(ActionEvent evt) {
                    CollideBall b = new CollideBall(canvas.getSize().width,canvas.getSize().height
                            ,INIT_X,INIT_Y,speedToSet,speedToSet,Color.BLUE,xxxx);
                    balls.add(b);
                    b.start();
            contentPane.add(canvas, "Center");
            contentPane.add(p, "South");
        public void addButton(Container c, String title, ActionListener a) {
            JButton b = new JButton(title);
            c.add(b);
            b.addActionListener(a);
        public boolean collide(CollideBall b1, CollideBall b2) {
            double wx=b1.getCenterX()-b2.getCenterX();
            double wy=b1.getCenterY()-b2.getCenterY();
            //we calculate the distance between the centers two
            //colliding balls (theorem of Pythagoras)
            double distance=Math.sqrt(wx*wx+wy*wy);
            if(distance<b1.diameter)
                return true;
            return false;
        synchronized void repairCollisions(CollideBall a) {
            for (CollideBall x:balls) if (x!=a && collide(x,a)) {
                x.hit(a);
                a.hit(x);
        public static void main(String[] args) {
            JFrame frame = new BouncingBalls();
            frame.setVisible(true);
    }  And when i press start button:
    Exception in thread "Thread-2" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-3" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-4" java.lang.NullPointerException
    at fuck.CollideBall.run(CollideBall.java:153)
    and line 153 is: balls.canvas.repaint(); in Method run() in First class.
    Please help.

    public RepaintManager manager;
    public BouncingBalls() {
            manager = new RepaintManager();
            manager.addDirtyRegion(canvas, 0, 0,canvas.getSize().width, canvas.getSize().height);
        public void run() {
            while(true) {
                try {Thread.sleep(15);} catch (Exception e) { }
                synchronized(balls)
                    move();
                    balls.repairCollisions(this);
                paint(balls.gBuffer);
                balls.manager.paintDirtyRegions(); //////// line 153
       but when push start:
    Exception in thread "Thread-2" java.lang.IllegalMonitorStateException
    at java.lang.Object.notifyAll(Native Method)
    at fuck.CollideBall.run(CollideBall.java:153)
    Exception in thread "Thread-3" java.lang.IllegalMonitorStateException
    at java.lang.Object.notifyAll(Native Method)
    at fuck.CollideBall.run(CollideBall.java:153)
    i'm newbie with Concurrency and i cant handle this exceptons.
    Is this the right way to do repaint?

  • Alternative to Double-Buffered Canvas

    I am working on a program in which I use a double-buffered Canvas inside a JScrollPane. The problem is that the Canvas draws over the scrollbars. I have tried extending JComponent, JPanel, JApplet, and Component instead of Canvas, and none of them are double buffered. Here is the code I used to debug this problem:
    import java.awt.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class Test implements  Runnable
         JFrame f;
         JScrollPane scroller;
         JPanel panel;
         TestCanvas canvas;
         Thread runner;
         BufferStrategy strategy;
         public static void main (String[] args) {
              Test app = new Test();
              app.init();
         public void init() {
              f = new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              panel = new JPanel();
              canvas = new TestCanvas();
              panel.add(canvas);
              scroller = new JScrollPane(panel);
              scroller.setWheelScrollingEnabled(true);
              f.getContentPane().add(scroller);
              f.pack();
              f.setSize(300,300);
              f.setVisible(true);
              canvas.createBufferStrategy(2);
              strategy = canvas.getBufferStrategy();
              runner = new Thread(this);
              runner.run();
         public void run() {
              int x = 0;
              while(x != 65536) {
                   Graphics2D g = (Graphics2D)strategy.getDrawGraphics().create();
                   g.setColor(new Color(x%256,0,0));
                   g.fill(new Ellipse2D.Double(0,0,600,600));
                   strategy.show();
                   x++;
    }Any suggestions?

    The main culprit is that you are mixing AWT components with Swing ones.
    In addition, your are doing so many of useless things and wrong things in your code.
    Swing components are defaulted for using double-buffering.
    See: http://java.sun.com/products/jfc/tsc/articles/painting/index.html
    Try and study this code.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.awt.image.*;
    import javax.swing.*;
    public class Fox1229{
      JFrame f;
      JScrollPane scroller;
      TestCanvas canvas;
      int x;
      Timer t;
      public static void main (String[] args) {
        Fox1229 app = new Fox1229();
        app.init();
      public void init() {
        x = 0;
        f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        canvas = new TestCanvas();
        scroller = new JScrollPane(canvas);
        scroller.setWheelScrollingEnabled(true);
        f.getContentPane().add(scroller, BorderLayout.CENTER);
        f.setSize(300, 300);
        f.setVisible(true);
        t = new Timer(50, new ActionListener(){
          public void actionPerformed(ActionEvent e){
            canvas.setOc(new Color(x % 256, 0, 0));
            canvas.repaint();
            if (++x == 1024){
              t.stop();
        t.start();
    class TestCanvas extends JPanel{
      Color oc;
      public TestCanvas (){
        oc = new Color(0, 0, 0);
      public void setOc(Color c){
        oc = c;
      public Dimension getPreferredSize(){
        return new Dimension(600, 600);
      public void paintComponent(Graphics g){
        super.paintComponent(g);
        Graphics2D g2d = (Graphics2D)g;
        g2d.setColor(Color.blue);
        g2d.fill(new Rectangle(0, 0, 600, 600));
        g2d.setColor(oc);
        g2d.fill(new Ellipse2D.Double(0, 0, 600, 600));
    }

  • Dynamically add remove table from a scrollpane

    Hi,
    I have a tree of different objects. And have tables for presenting the information of those objects. When i click on the tree node i want the corresponding table to be loaded in the jscrollpane. Is this possible.
    Till now this is my code.,
    tableModel.setObj1(obj1);
         scrollPane.removeAll();
         repaint();
         scrollPane.add(table);
         validate();
    But this does not show up the table, it is blank.
    Any thoughts is greatly appreciated
    Thanks

    forget this post,
    I got the answer
    Thanks

  • Repaint() method 's not work but paint(getGraphics()) does, why?

    I've just read the following code ( in the Core Java 2 advance features vol 2 book):
      import java.awt.*;
      import java.awt.event.*;
       import java.awt.geom.*;
       import java.util.*;
       import javax.swing.*;
          Shows an animated bouncing ball.
      public class Bounce
         public static void main(String[] args)
            JFrame frame = new BounceFrame();
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.show();
         The frame with canvas and buttons.
      class BounceFrame extends JFrame
            Constructs the frame with the canvas for showing the
            bouncing ball and Start and Close buttons
         public BounceFrame()
            setSize(WIDTH, HEIGHT);
            setTitle("Bounce");
            Container contentPane = getContentPane();
            canvas = new BallCanvas();
            contentPane.add(canvas, BorderLayout.CENTER);
            JPanel buttonPanel = new JPanel();
            addButton(buttonPanel, "Start",
               new ActionListener()
                     public void actionPerformed(ActionEvent evt)
                        addBall();
            addButton(buttonPanel, "Close",
               new ActionListener()
                     public void actionPerformed(ActionEvent evt)
                       System.exit(0);
            contentPane.add(buttonPanel, BorderLayout.SOUTH);
            Adds a button to a container.
            @param c the container
            @param title the button title
            @param listener the action listener for the button
         public void addButton(Container c, String title,
            ActionListener listener)
            JButton button = new JButton(title);
            c.add(button);
            button.addActionListener(listener);
            Adds a bouncing ball to the canvas and makes
            it bounce 1,000 times.
         public void addBall()
            try
               Ball b = new Ball(canvas);
               canvas.add(b);
               for (int i = 1; i <= 1000; i++)
                  b.move();
                  Thread.sleep(5);
            catch (InterruptedException exception)
         private BallCanvas canvas;
         public static final int WIDTH = 450;
         public static final int HEIGHT = 350;
        The canvas that draws the balls.
    class BallCanvas extends JPanel
            Add a ball to the canvas.
            @param b the ball to add
       public void add(Ball b)
           balls.add(b);
        public void update(Graphics g) {
             super.update(g);
             System.out.println("Test");
        public void paintComponent(Graphics g)
          super.paintComponent(g);
          Graphics2D g2 = (Graphics2D)g;
          for (int i = 0; i < balls.size(); i++)
             Ball b = (Ball)balls.get(i);
             b.draw(g2);
            // System.out.println("Test");
        private ArrayList balls = new ArrayList();
        A ball that moves and bounces off the edges of a
       component
    class Ball
            Constructs a ball in the upper left corner
            @c the component in which the ball bounces
        public Ball(Component c) { canvas = c; }
           Draws the ball at its current position
           @param g2 the graphics context
        public void draw(Graphics2D g2)
           g2.fill(new Ellipse2D.Double(x, y, XSIZE, YSIZE));
          Moves the ball to the next position, reversing direction
          if it hits one of the edges
       public void move()
          x += dx;
          y += dy;
           if (x < 0)
              x = 0;
              dx = -dx;
         if (x + XSIZE >= canvas.getWidth())
             x = canvas.getWidth() - XSIZE;
              dx = -dx;
           if (y < 0)
             y = 0;
              dy = -dy;
           if (y + YSIZE >= canvas.getHeight())
              y = canvas.getHeight() - YSIZE;
              dy = -dy;
           //canvas.paint(canvas.getGraphics());//this would OK.
           canvas.repaint();//This not work, please tell me why?
        private Component canvas;
        private static final int XSIZE = 15;
       private static final int YSIZE = 15;
       private int x = 0;
       private int y = 0;
       private int dx = 2;
       private int dy = 2;
    }this program create a GUI containing a "add ball" button to creat a ball and make it bounce inside the window. ( this seems to be stupid example but it is just an example of why we should use Thread for the purpose ).
    Note: in the move() method, if i use canvas.repaint() then the ball is not redrawn after each movement. but if i use canvas.paint(canvas.getGraphics()) then everythings seem to be OK.
    Another question: Still the above programe, but If I create the ball and let it bounce in a separate thread, then canvas.repaint() in the move method work OK.
    Any one can tell me why? Thanks alot !!!

    I don't know why the one method works. Based on my Swing knowledge neither method should work. Did you notice that the JButton wasn't repainted until after the ball stopped bouncing. That is because of the following code:
    for (int i = 1; i <= 1000; i++)
        b.move();
        Thread.sleep(5);
    }This code is attempting to move the ball and then sleep for 5 milliseconds. The problem with this code is that you are telling the Event Thread to sleep. Normally painting events are added to the end of the Event Thread to allow for multiple painting requests to be combined into one for painting efficiency. When you tell the Thread to sleep then the GUI doesn't get a chance to repaint itself.
    More details about the EventThread can be found in the Swing tutorial:
    http://java.sun.com/docs/books/tutorial/uiswing/misc/threads.html
    This explains why the button isn't repainted, but it doesn't explain why the ball bounces. I don't know the answer to this for sure, but I do know that there is a method called paintImmediately(...) which causes the painting to be performed immediately without being added to the end of the Event Thread. This means the painting can be done before the Thread sleeps. Maybe the canvas.paint(....) is somehow invoking this method.
    When you click on the button this code is executed in the EvWell in Swing, all GUI painting is done on the Event Thread

  • How to avoid repaint?

    I am making a simple drawing application. I have Canvas and a JPanel with 2 JcomboBoxes(to chose color and thickness of line) on it.
    I can do drawing, but when I click on any of Comboboxes to chose a color, for example, I get my Canvas repainted(maybe), my drawings disappear. The same is if I put any other application over it.
    How could I fix it? Could you help me please?
    Roman.

    You are still using the getGraphics() method, nothing else. You should do the drawing in the paint method instead:import java.awt.*;
    import java.awt.event.*;
    public class CCanvas extends Canvas {
        Point startpoint, endpoint;
        public CCanvas() {
            addMouseMotionListener(new DrawingListener());
        public void paint(Graphics g) {
            g.drawLine(startpoint.x, startpoint.y, endpoint.x, endpoint.y);
        class DrawingListener extends MouseMotionAdapter {
            public void mouseDragged(MouseEvent e) {
                endpoint = e.getPoint();
                repaint(); // update the canvas
                startpoint = endpoint;
    }The graphics object will be cleared before paint is called so that the line that is painted earlier will be lost. If you don't want that to happen you'll have to override the update-method too:    public void update(Graphics g) {
            paint(g);

  • JScrollPane doesn't adjust itself to the view component

    I have an applet that shows a JPanel in JScrollPane:
    form the applet:
    public void init() {
    getContentPane().setLayout(new BorderLayout());
    panel = new SnapCanvas(); //snapCanvas extends JPanel and is not a Canvas
    drawGraph(graph);
    jScrollPane = new JScrollPane(canvas);
    getContentPane().add(jScrollPane, BorderLayout.CENTER);
    setVisible(true);
    canvas.repaint();
    Now this works fine, but if the JPanel's (called canvas in the code) prefered size is changed the scroll pane doesn't adjust itself. What do I do in order for the JScrollPane to adjust when the JPanel is changed?
    Thanks

    foubd the solution in http://java.sun.com/docs/books/tutorial/uiswing/components/scrollpane.html#sizing

Maybe you are looking for

  • A Mighty Mouse and a Mighty 1 year Old Clash

    I've got a mouse question about, uh, the Mighty Mouse (the one that allows has five buttons, and a scroll dot. it was included in my quad purchase a couple of months back). My one year old son likes the red light underneath my mouse, and will try to

  • Exporting original from photo booth

    From what I could find export original is to export an image without the effect, correct? Why is an 4 image file in photo booth not allowed to select export original then?

  • How to add JDBC Driver to my CLASSPATH

    Hi~ I use MySQL JDBC Driver in my program like that Class.forName("com.mysql.jdbc.Driver");But when I try to run it, I got a ClassNoFound Exception,I hava add mysql-connector-java-5.0.3-bin.jar into my CLASSPATH, but it no use.How to fix it ? Thanks

  • HELP! Error message: itunes not communicating

    After installing itunes 5.0, I got this message: "The software required for communicating with the ipod is not installed correctly. Please reinstall itunes to install the ipods software." I reinstalled 5.0 twice, and 5.0.1 twice, then uninstalled itu

  • Will I lose everything if I do a factory reset

    My iPhone 5 backup is corrupt, I'm told that I have a factory reset. I have a Macbook pro and a Desktop with my Notes, Photos, Contacts... am I forgeting anything?