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 ?

Similar Messages

  • J2ME game gui? J2ME Canvas? J2ME polish? Which is better?

    I am currently trying to build a J2ME brochure like project which is required to have rich presentation.
    JAVA is not a problem for me as I've used it for quite a long time. But since I am very new in J2ME, I am confused which technology to use, should I use j2me game gui, j2me canvas or j2me polish?
    Using j2me game gui looks good. J2me canvas looks a bit tedious to me because for a brochure like project, it will mean I will probably end up using a lot of canvas which make the application quite big. Regarding to J2ME polish, there is not many materials or examples about it. it seems that J2ME polish hasn't been used a lot and I don't know whether it's good or not.
    Anybody knows something about those three? Please give me a hand.
    Thanks.

    J2ME Polish have licensing costs associated with it:
    http://www.j2mepolish.org/licenses.html
    As for Canvas VS GameCanvas:
    GameCanvas is MIDP 2.0 and up, so depending which devices your app supports you might want to stick with Canvas. GameCanvas eases graphics flushing, but double buffering can be implemented on Canvas like so:
    Image offscreen = isDoubleBuffered () ? null :
               Image.createImage (getWidth (), getHeight ());See http://www.developer.com/java/j2me/article.php/10934_1561591_8
    section: Avoiding Flickering

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

  • (Java ME/J2me) Canvas Vertical Scroll Problem

    Hi i have spent a couple of days creating a small canvas bassed application i hours on a glitch trying to figure out why the myscreen.translate() will not let me scoll down verticly more than two pages can anyone see the problem ?
    import javax.microedition.lcdui.*;
    public class MobileLifeList extends Canvas {
    private Font Myfont = Font.getDefaultFont();
    private int LEFTSOFTKEYCODE =  -6;
    private int RIGHTSOFTKEYCODE = -7;
    private String[] ListItems;
    private Image[] ListImages;
    private int SelectedIndex = 0;
    MobileLife midlet;
    private int Amount = 0;
    public int mywidth;
    public int myheight;
    private int PageMode;
    public int ooscounter;
    private int MyPerPage;
    public int Page = 1;
    MobileLifeList(MobileLife mymidlet,String[] items,Image[] images){
    this.midlet     = mymidlet;
    this.ListItems  = items;
    this.ListImages = images;
    protected void paint(Graphics myscreen){
    int mywidth = myscreen.getClipWidth();
    int myheight = myscreen.getClipHeight();
    myscreen.setColor(0xffffff); //WHT
    myscreen.fillRect(0,0,mywidth,myheight);
    MyPerPage = myheight/Myfont.getHeight() - 1 * Page;
    if(ooscounter>=MyPerPage){
    myscreen.translate(0,-myheight * Page);
    for(int i=0; i<=ListItems.length - 1; i++){
    if(i!=ListItems.length){
    if(SelectedIndex==i){
    myscreen.setColor(0x000000); //BLK
    } else {
    myscreen.setColor(0xFFFFFF); //BLK
    myscreen.fillRect(0,(Myfont.getHeight() + 1) * i,mywidth,Myfont.getHeight());
    if(SelectedIndex==i){
    myscreen.setColor(0xFFFFFF); //BLK
    } else {
    myscreen.setColor(0x000000); //BLK
    myscreen.drawString(ListItems,0,(Myfont.getHeight() + 1) * i, Graphics.TOP|Graphics.LEFT);
    protected void keyPressed(int keyCode) {
    String TheMobileAgent = System.getProperty("microedition.platform");
    if(TheMobileAgent.indexOf("Vodafone")>=0 || TheMobileAgent.indexOf("Panasonic/X60")>=0 || TheMobileAgent.indexOf("Sharp")>=0 || TheMobileAgent.indexOf("Panasonic/X60")>=0){
    LEFTSOFTKEYCODE = 21;
    RIGHTSOFTKEYCODE = 22;
    if(TheMobileAgent.indexOf("Motorola")>=0 || TheMobileAgent.indexOf("GX15")>=0 || TheMobileAgent.indexOf("GX25")>=0){
    LEFTSOFTKEYCODE = -21;
    RIGHTSOFTKEYCODE = -22;
    if(TheMobileAgent.indexOf("Siemens")>=0){
    LEFTSOFTKEYCODE = -1;
    RIGHTSOFTKEYCODE = -4;
    if(TheMobileAgent.indexOf("Sagem")>=0){
    LEFTSOFTKEYCODE = -7;
    RIGHTSOFTKEYCODE = -6;
    if(TheMobileAgent.indexOf("Qtek")>=0 || TheMobileAgent.indexOf("T-Mobile/MDA")>=0|| TheMobileAgent.indexOf("Verizon/XV8600")>=0 || TheMobileAgent.indexOf("Samsung/Blackjack")>=0) {
    LEFTSOFTKEYCODE = 57345;
    RIGHTSOFTKEYCODE = 57346;
    if(TheMobileAgent.indexOf("Sony-Ericsson/W910i")>=0 || TheMobileAgent.indexOf("Nokia/2630") >=0|| TheMobileAgent.indexOf("Nokia/3110_classic") >=0 || TheMobileAgent.indexOf("Nokia/3110c") >=0 || TheMobileAgent.indexOf("Nokia/3500_classic") >=0){
    LEFTSOFTKEYCODE = -3;
    RIGHTSOFTKEYCODE = -4;
    if(TheMobileAgent.indexOf("Sony-Ericsson/M")>=0|| TheMobileAgent.indexOf("Sony-Ericsson/P")>=0){     
    LEFTSOFTKEYCODE = -7;
    RIGHTSOFTKEYCODE = -6;
    if(TheMobileAgent.indexOf("Samsung/B2700")>=0){          
    LEFTSOFTKEYCODE = -5;
    RIGHTSOFTKEYCODE = -7;
    if(TheMobileAgent.indexOf("Sony-Ericsson/T303")>=0){
    LEFTSOFTKEYCODE = -6;
    RIGHTSOFTKEYCODE = -10;
    if(keyCode==LEFTSOFTKEYCODE){
    System.out.println("LEFT softkey Pressed");
    MobileLifeCanvas mListCanvas = new MobileLifeCanvas(midlet);
    Display.getDisplay(midlet).setCurrent(mListCanvas);
    if(keyCode==RIGHTSOFTKEYCODE){
    System.out.println("Right softkey Pressed");
    int act = getGameAction(keyCode);
    int PerPage = myheight/Myfont.getHeight() - 1;
    if(act==Canvas.UP){
    if(SelectedIndex > 0){
    SelectedIndex--;
    ooscounter--;
    if(act==Canvas.DOWN){
    if(SelectedIndex != ListItems.length - 1){
    SelectedIndex++;
    ooscounter++;
    System.out.println("Index:" + SelectedIndex);
    repaint();
    Thankyou,
    Rob                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    ...how can i access myscreen varible outside of my paint function?Why don't you call the variable myGraphics? myscreen is a confusing name for a variable that refers to Graphics object because there's quite a different class Screen in MIDP API.
    As for accessing Graphics from outside of paint, I am not sure if that's a good idea. If memory serves, it can change in different invocations of paint (check the Canvas class javadocs for details if you're interested).
    To have a reliable reference to Graphics, I would rather use GameCanvas (it's a subclss of Canvas with some additional features).

  • 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

  • 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

  • J2ME Canvas and Form Objects

    I am currently in the process of converting an existing MIDP application which uses the standard high-level UI to implement menus and form objects.
    I am converting this to use the low-level UI with canvases to make the application look far more professional. There seem to be no decent tutorials realting to using the canvas to with relation to menus or user input.
    Is it possible to add the standard TextField and ChoiceGroup types into a canvas? If not, how are these implemented in existing MIDP applications that clearly use a canvas.
    Thanks for any help that you might be able to give,
    Dave

    umm abit of athread revivial but it seems that using j2me polish is more hard work than using standard j2me. This is because you need to know abit of xml and css to take full advantage of j2me polish.
    still is that the only way to create a form in a canvas?

  • 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

  • Timer in j2me canvas

    Hi,
    I want to implement timer in my mobile game,that will start from 5and go to 0
    timer will show hours:min:sec:milisec
    on screeen .
    plz tell me if anybody know

    Hi,
    You can start a separate Thread that keeps updating the time drawn on the Canvas. You are working with which version of MIDP ?
    -Priyanka

  • How to draw  blinking coursor on J2ME canvas.?

    Hi..esperts
    I have draw a TextField on canvas. i want to draw a blinking cursor on TextField also.
    cursor will change position as characters are drawn in TextField .
    how i can do that.
    please suggest me.
    Thanks and Regards

    Don't cross post. Once is enough.
    I'm locking this thread. All responses on
    [http://forums.sun.com/thread.jspa?threadID=5345819]
    db

  • A question about j2me Canvas?

    I want to draw a n-point ploygon, and fill some color in this ploygon, please help me, I cannot get a way to solve this problem?

    Hi , I hava download jmicropolygon_midp2-1.0.jar.
    and use
    private int[] xpoint = { 10, 100, 100, 50, 50, 30, 30, 10,10 };
    private int[] ypoint = { 10, 10, 70, 70, 40, 40, 100, 100,10 };
    g.setColor(255, 255, 255);
         g.fillRect(0, 0, getWidth(), getHeight());
         g.setColor(255,0,0);
         PolygonGraphics.drawPolygon(g,xpoint,ypoint);
    but it doesn't work.
    can you tell me how to use it?
    Thanks!!

  • J2ME Canvas grid

    I'm using that two classes to generate a table:
    http://isengard.metal.pl/TableCanvas.java
    and
    http://isengard.metal.pl/ScrollableTable.java
    (the first one uses the second)
    The table is fullscreen but I'd like it to get only 90% of screen heigth and on the top of screen I'd like to put an information about f.e. internet connection etc. The problem is because I've found this Java code illegible and don't know how to move the table to the bottom for a approximately 15 px so that on the top I'd get more place for text. Could you please give me any ideas what should I change?
    thank you

    Hi, I finally managed to get it to run on my machine (the line vec.copyInto(array); in the TableCanvas constructor threw an exception for me, apparently it doesn't like 2D arrays, so I'm suprised it works for you). But anyway, with the changes I mentioned before it works perfectly fine.
    The TableCanvas paint method:
    protected void paint(Graphics g) {
              g.setColor(0xffffff);
              g.fillRect(0, 0, getWidth(), getHeight());
              g.translate(10, 25);
              g.setFont(Font.getFont(Font.FACE_MONOSPACE, Font.STYLE_PLAIN, Font.SIZE_SMALL));
              table.paint(g);
              g.translate(-10, -25);
              g.drawString("test", 60, 0, Graphics.TOP|Graphics.LEFT);
         }The ScrollableTable paint method:
    public void paint(Graphics g) {
            int cX = g.getClipX();
            int cY = g.getClipY();
            int cW = g.getClipWidth();
            int cH = g.getClipHeight();
            g.setClip(0, 0, viewportWidth, viewportHeight +10);
            g.translate(-viewportX, -viewportY);
            g.setColor(bgColor);
            g.fillRect(0, 0, width, height);
            int currentX = 0;
            int currentY = 0;
            for (int i = 0; i < rows; i++) {
                currentX = 0;
                g.setColor(borderColor);
                g.fillRect(0, currentY, width, borderWidth);
                currentY += borderWidth;
                for (int j = 0; j < cols; j++) {
                    if (i == 0) {
                        g.setColor(borderColor);
                        g.fillRect(currentX, 0, borderWidth, height);
                    if (j == currentCol && i == currentRow) {
                        g.setColor(bgFocusedColor);
                        g.fillRect(borderWidth + currentX, currentY, colWidths[j], rowHeights);
    g.setColor(foreColor);
    currentX += borderWidth;
    g.setColor(foreColor);
    for (int k = 0; k < dataRows[i][j].length; k++) {
    g.drawString(dataRows[i][j][k], padding + currentX, padding + currentY + k * (font.getHeight() + interline), Graphics.TOP | Graphics.LEFT);
    currentX += colWidths[j];
    if (i == 0) {
    g.setColor(borderColor);
    g.fillRect(currentX, 0, borderWidth, height);
    currentY += rowHeights[i];
    g.setColor(borderColor);
    g.fillRect(0, currentY, width, borderWidth);
    g.translate(viewportX, viewportY);
    g.setColor(this.foreColor);
    g.setClip(cX, cY, cW, cH);
    }I have added in g.setColor(foreColor); because otherwise the title would be drawn using the border colour.  And as I said for me it worked fine.  So I'm not sure why it is not working for you.  Try copying the above code exactly into your code and see if there is any difference, if it still does not work then you could send me your files and I'll have a look on my machine if I can get it to work.
    p.s. what emulator and IDE are you using?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Which one is better to use..Canvas or J2ME Polish

    Hello Frnds,
    I want to add background images n want to use High level GUI, So is the polish be a good option for it , or should I go for simple j2me canvas n write my own low level... GUI like construct .....or should go for Synclast 3rd party API. library......

    I've J2ME Polish on a few projects, and it can be really nice. But sometimes you just need more, you need pure Canvas flexibility. And for that (and for 90% of my projects) I use synclast. It's a canvas based container toolkit, it allows you to do a LOT with a canvas, and you can also extend it very easily to create your own widgets for the UI.
    http://synclast.com/ui_api.jsp
    don't download the release build, it's REALLY old, download the source and compile your own jar for a much more up-to-date library.

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

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

Maybe you are looking for

  • Ical 5. Events not displaying

    Morning. So, Lion is in. Was adding events to Ical5 the other day, and all was going well. These are all normal full day events, that are non re-occuring, and all on my mobileme calendar. (I do have a valid mobile me account and such as well) Made it

  • Re: Installation issue in second install on home computer?

    I have second computer at home. I have CC at my office. Yes I know I can install on the second computer. Please tell me how this occurs? Do I have to remove all trail versions of Adobe software before I can install on the home computer?

  • How To debug ABAP code using sapui5 application on NWBC

    Hi All I am working on NWBC with SAP_PAO_HRPROFESSIONAL_3 Role. This role contains SAPUI5 application. I am trying debug the ABAP code called while executing this application. Please help me how to get into ABAP debugger while executing this applicat

  • 3.2; BC4J, GridControl; Select row programatically?

    Hi, I need to programatically Highlighted a desired row (which i know the primary key) from a grid and scroll the grid to show this selected row in the view port area. Any property/way for this ? note that: define a WHERE clause for rowSetInfo and .e

  • Using realtime metrics in plugin pages

    I'm using realtime refresh interval for a plugin page and it works great. The problem I have is that if target is down, the components using realtime metrics produce an error in the pop-up dialog due to realtime collection error (like connection refu