AWT repaint() in Jeode VM

Any idea why isnt update(Graphics g) invoked upon repaint() in updateLocation?? The device is HP IPAQ, Jeode VM, PersonalJava 1.2 Thanks. Below is the code for the class that draws the image. Somehow the printlns never produced checkpoint 2.1 when repaint() is called.
     public void updateLocation(VTourLocation vtourLocation, Dimension dim){                      
          this.vtourLocation = vtourLocation;           
          this.locX = vtourLocation.getX();
          this.locY = vtourLocation.getY();
          if(!startFlag || vtourLocation.isNewContext()){
               byte[] map = vtourLocation.getImage();                                                                                
               currentImg = Toolkit.getDefaultToolkit().createImage(map);                
               try{
                    MediaTracker tracker = new MediaTracker(this);
                   tracker.addImage(currentImg,1);
                  tracker.waitForID(1);
              catch(InterruptedException e){
                   System.out.println(e);
              catch(NullPointerException nullE){
                   System.out.println("Something is wrong");
                   System.exit(1);
               fitToScreen(dim);                                                
               System.out.println("checkpoint 1");
               initBufferGraphics();
               startFlag = true;
               System.out.println("checkpoint 2");                
          repaint();
     public void update(Graphics g){               
          paint(g);               
     public void paint(Graphics g){          
          System.out.println("checkpoint 2.1");                                                       
          bufferGraphics.setColor(this.getBackground());
          bufferGraphics.fillRect(0, 0, bufferImgWidth, bufferImgHeight);     
          bufferGraphics.drawImage(currentImg,0,0, scaledImgWidth, scaledImgHeight, this);          
          System.out.println("checkpoint 2.2");               
          if(startFlag){          
               System.out.println("checkpoint 3");
               bufferGraphics.setColor(Color.green);
               bufferGraphics.fillRect(scaledLocX, scaledLocY, scaledRectSize,
                    scaledRectSize);                                                                  
          g.drawImage(bufferImg,0,0,this);                                        

Strange even when I commented the update method. Repaint does not work!?! Somehow the code stops going into Paint(Graphics g) but no exception is thrown. Can someone help? Will really appreciate it.

Similar Messages

  • AWT repaint() not Working

    The Cdoe Given Below is not responding to the action of okBtn
    It removes the center1Panel
    but does not adds or repaints the added center2Panel
    Wher am I wrong?
    Help Me
    import java.awt.BorderLayout;
    import java.awt.Button;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Frame;
    import java.awt.Panel;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    public class ExamFrame extends Frame implements ActionListener{
         Button okBtn= new Button("OK");
         Panel mainPanel = new Panel();
         Panel southPanel = new Panel();
         Panel northPanel = new Panel();
         Panel centerPanel = new Panel();
         Panel center1Panel = new Panel();
         Panel center2Panel;
         public ExamFrame() {
              super("Exam");
              setBackground(Color.gray);
              southPanel.add(okBtn);
              mainPanel.setLayout(new BorderLayout());
              mainPanel.add(southPanel,BorderLayout.SOUTH);
              mainPanel.add(northPanel,BorderLayout.NORTH);
              mainPanel.add(centerPanel,BorderLayout.CENTER);
              centerPanel.setPreferredSize(new Dimension(400,600));
              southPanel.setBackground(Color.red);
              center1Panel.setBackground(Color.blue);
              center1Panel.setPreferredSize(new Dimension(400,600));
              center2Panel = new Panel();
              center2Panel.setBackground(Color.green);
              center2Panel.setPreferredSize(new Dimension(400,600));
              centerPanel.add(center1Panel);
              centerPanel.add(center2Panel);
              okBtn.addActionListener(this);
              add(mainPanel);
              this.addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
         public void actionPerformed(ActionEvent ae) {
              // TODO Auto-generated method stub
              if(ae.getSource()==okBtn){
                   centerPanel.removeAll();
                   repaint();
                   center2Panel= new Panel();
                   center2Panel.setBackground(Color.green);
                   center2Panel.setPreferredSize(new Dimension(400,600));
                   centerPanel.add(center2Panel);
                   centerPanel.repaint();
                   repaint();
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              ExamFrame frame= new ExamFrame();
              frame.setSize(new Dimension(600,400));
              frame.setVisible(true);
    }

    You need to usecenterPanel.validate();instead ofcenterPanel.repaint();db

  • Graphics update problem

    I have an applet which contains different part like panel and canvas.
    I have a main program which is sthg like:
    public void run() {
    thread thisThread = Thread.currentThread ();
    while (is == thisThread) {
    long startTime = System.currentTimeMillis ();
    substhg.dosomething();
    repaint();
    can.repaint(); //added in the hope it would work then
    Thread.currentThread ().sleep (timeout);
    so the program does something, paints that something and sleeps a while. in IE and most Netscape-Version that works. But in the applet-viewer and in NS 6.2 it draws the thing but then "stands still" and doesnt change anything till i change to another window and back (then it changed but only once) - so internally it works but it doesnt draw it correctly. - same for this netscape-version under linux!
    any idea, whats wrong?
    thanks a lot!

    The awt runs an event handler Thread that processes all event and does repainting. If you sleep in an event, you sleep the repainting thread, as the previous poster stated. One solution to this is to make your own Thread, off of the AWT Thread and generate repaint event when need from there. A very common way to do this is to make an "offscreen" image and draw to it in your thread, then call the awt repaint to throw it up to the screen at some predifined "framerate"
    http://java.sun.com/docs/books/cp/

  • Rendering Issues Windows XP

    Hi,
    I am completely stumped with a repaint issue in my app.
    The application is a fullscreen app. There are JDialogs which appear on top of the main fullscreen JFrame from time to time. All windows are undecorated!
    The problem is that sometimes the dialogs do not show and sometimes it looks like they do not disappear after being closed. However, if i rub my finger over the screen (touchscreen) then bits of the dialog will either appear/disappear as appropriate. That means it is a rendering /repaint issue ..
    The times when this problem occurs are extremely random. Some installs may not notice for upto one year then it could happen a few times in a week..
    All of my GUI code is called from within the EDT thread and i use the swinghelper class CheckThreadViolationRepaintManager to ensure that this is always the case. This should mean i have no repaint problems such as are happening. The EDT is not stuck either when these repaint issues occur as i monitor that to ensure this.
    I also set the flag -Dsun.java2d.noddraw=true which i have read can fix some rendering issues on win32 installs. However this does not appear to fix it in all situations.
    My biggest problem is how to debug this? Are there any other reasons why this might happen?
    Thanks in advance..
    BTW: the majority of the jvm's this happen on are 1.6_16 but i also have one running 1.6_22 (latest i think!)

    I already wrapped any calls to JDialogs.setVisible(true) with SwingUtilities.invokeLater
    I did this even though they are all created and shown on the EDT as they are called from an ActionEvent handler (can the actionevent generated by clicking a button be called from something other than the EDT? As far as i am aware it cannot).
    i have frequent checks in code to check if we are running on the EDT and log a warning if we're not. When this issue occurs there is no warning in the logs about not being on the EDT anywhere!. I use SwingWorker where necessary to take any extra load off the EDT.
    JDialog.toFront() should not do anything since it is modal (APPLICATION_MODAL) so it should be on top anyway.
    This would only be something todo with showing the dialog. Not closing and then repainting the main frame behind it. All calls to JDialog.dispose() are wrapped by java.awt.Window.doDispose() to be on the EDT even if they are not called from the EDT.
    These are all standard Swing/AWT repaint issues that i am aware of. Is there any other non standard ways this issue can arise?

  • Repaint/Refreshing AWT components

    Hi there,
    I'm writing a chess game and for the GUI I've added 8x8 panels into a frame with a grid layout. Currently I'm just using labels for the pieces, in the middle of panels. I'm having a problem updating my GUI after a move has been made - a call to repaint() does nothing. I'm just using basic AWT.
    I've also tried removeAllComponents() of the frame and adding them again with the updated data, but nothing happens - I just lose all my panels. Can anyone help please?
    Many thanks!

    scsi-boy :
    I want to have a more general method of refreshing the
    graphics so that later if/when I 'upgrade' to using
    images (or whatever) instead of labels I can simplyi believe my suggestion is certainly compatible with that.
    adapt it. I would think that calling setText for the
    Labels would mean that I would have to give the
    location of the panel as a parameter somewhere, and
    would also have to remove the label where the piece
    was previously (ie if a knight moves, I'd have to
    target its destination to setText and remove it from
    where it was).here is what i would do, please note that this will work with a variety
    of implementations including using all Graphics later on or whatever.
    // here we have a bunch of constants that represent the possible status
    // of board postions
    final int EMPTY_SPACE = 0;
    final int B_KING = 1;
    final int W_KING = 2;
    final int B_QUEEN = 3;
    final int W_QUEEN = 5;
    final int B_BISHOP = 6;
    final int W_BISHOP = 7;
    final int B_KNIGHT = 8;
    final int W_KNIGHT = 9;
    final int B_ROOK = 10;
    final int W_ROOK = 11;
    final int B_PAWN = 12;
    final int W_PAWN = 13;
    // the game board is used to store the status of all the postitions in
    // a game
    int[][] gameBoard;
    // the game display is the array of Labels that we use to present the
    // board in our GUI
    Label[][] gameDisplay;
    // in the constructor;
    gameBoard = new int[8][8];
    for(int i=0;i<gameBoard.length;i++){
      for(int j=0;i<8;j++){
        gameBoard[i][j] = EMPTY_SPACE;
    // here is where you would add the various pieces to gameBoard...
    gameDisplay = new Label[8][8];
      Now wherever you interaction and logic are you can use a method. You
      can call this method repaint(); so that it will be compatible with
      what you do later.
    public void repaint(){
      for(int i=0;i<gameBoard.length;i++){
        for(int j=0;j<8;j++){
          switch(gameBoard[i][j]){
            case B_KING:
              gameDisplayj].setText("Black King");
    break;
    case W_KING:
    gameDisplay[i]j].setText("White King");
    break;
    case B_QUEEN:
    gameDisplay[i]j].setText("Black Queen");
    break;
    // and so on and so forth... until
    default:
    gameDisplay[i]j].setText("");
    anyway the above code is just a sample of how you can build this so you
    can seperate out your logic from your GUI so you can change your GUI
    later without hassle.
    finally i would ask how are you changing the text on the screen. are you
    creating new Labels and sticking them in the Panels? i suspect something
    like this... don't do that. two reasons, one as you may have noticed it
    doesn't work that way or you have to use some sort of hack to get it to
    work and two it's more efficient in terms of memory and speed if you
    re-use the awt ot Swing components by making use of methods such as
    setText rather than creating new objects each time.
    i hope you find this helpful.

  • How to prevent the automatic full-white repainting of an AWT Frame?

    Using Java 1.6.0, Windows XP, 1.6.0-b105 Client VM I have the following problem:
    I made a double buffered AWT frame. But it still flashes sometimes. It gives one flash about 6 seconds after start of application. There seems to be an incoming event "for no discernible reason". I have overridden all paint/repaint/update methods in my Frame sub class.
    These unwanted flashes are caused by the AWT painting the frame in white and then calling paint.
    I may have caught these weird calls:
    The good/normal case looks like:
    java.lang.Exception: Stack trace
    at java.lang.Thread.dumpStack(Thread.java:1206)
    at xed.xed_Frame.paint(xed_Frame.java:125)
    at xed.xed_Frame.update(xed_Frame.java:119)
    at sun.awt.RepaintArea.updateComponent(RepaintArea.java:239)
    at sun.awt.RepaintArea.paint(RepaintArea.java:216)
    at sun.awt.windows.WComponentPeer.handleEvent(WComponentPeer.java:301)
    at java.awt.Component.dispatchEventImpl(Component.java:4486)
    at java.awt.Container.dispatchEventImpl(Container.java:2116)
    at java.awt.Window.dispatchEventImpl(Window.java:2429)
    at java.awt.Component.dispatchEvent(Component.java:4240)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
    The differences in the bad case: (Not all traces of this kind cause the flashing. But after all flashes there seems to be such a trace.)
    at xed.xed_Frame.paint(xed_Frame.java:125)
    at sun.awt.RepaintArea.paintComponent(RepaintArea.java:248)
    at sun.awt.RepaintArea.paint(RepaintArea.java:224)
    at sun.awt.windows.WComponentPeer.handleEvent(WComponentPeer.java:301)
    So how do I stop these unwanted white redraws of the Frame?

    Accidentally found the answer:
    System.setProperty("sun.awt.noerasebackground", "true");

  • Repaint in AWT Component

    Could anybody tell me, haw can i do so, that when one component is overlapped by another one, and after that the first component will be visible again, i do not need to repaint (a part of) the first component?

    CardLayout can unfortunaly display only one card at the same time. I m talking about my derived classes from JPanel. But i need all my objects be displayd at same time, may be overlapped(they are all dragable). And it were super, if paint(Graphics) would not be called each time, as "closed" object is visible again. Can i do so, that ovelapped area leaves in memory and dont need to be paint again. Or not?
    P.S. I am making a Drawing-like Tool, where PDF-rendering is needed. I could render only a PDF-area, that is currently needed. So i can zoom so much as i want without loss of quality. But unfortunaly this is to slaw and i need to optimize that.

  • Switching panels in AWT

    Hi, having a problem with switching 2 panels within a frame. Am using the following code within the frame file:
    removeAll();
    recPlay = new RecPlayPanel(tvacs);
    recPlay.start();
    add(recPlay);
    this.repaint();
    When this code is exectuted the first panel is removed but the second is not displayed, yet if you resize the frame it suddenly appears. Does anybody know why this happens. NOTE: this must be done using AWT components only as is to run on JEODE runtime. Thanks in advance, Alan

    You should probably call validate() since that'll set the size of the panel according to your layout policy.
    Hope this helps.

  • Focus on Jeode/MS PPC2002/personalJava

    Guys,
    I'd like to start a new thread that only focus on develop sorta more complex java application based on Jeode JVM from Insignia which follow the Sun Personal Java 1.2 specification that will run on PDA running MS PocketPC 2002 OS, such as iPAQ from HP/COmpaq, Axim from Dell, other device from Toshiba etc.
    this kind of topic is getting hotter since MIDP/CLDC is not that suitable for more advanced business application development. Why not we share (how many ppl are in this pool now?) our experience/idea/pain/joyness about this topic?
    Hope follow up post not only help us who is working on this right now but also give others who might join later a better orgainized place to start with,
    Cheers,
    Hong

    Some my pains on Jeode/MS PPC2002:
    1. Working dir is set to main folder "\" - I don't like it. I would like to know how to access files using relative path, not full path.
    2. no Runtime.exec() :(
    3. problems with AWT, threads - it's hard to describe a scenario, but sometimes there are strange problems when using advance AWT components. It looks like some performance problem with AWT, that processes which for example repaint or delete visual components works too slow, and sometimes in "main" thread you can access or not object which in a specific situation should be available or not. As I said, it's hard to explain exacly this problem. But if you have strange errors causing "segmentation fault" and are using complex GUI look at AWT and how it can "synchronize" with a rest of code.
    Interesting is that this problem was not present on Jeode/Linux/Sharp Zaurus.
    There was some of my problems with Jeode/PPC2002/iPAQ when I was writing application with about 30 000 lines of source code.
    regards,
    prusak

  • If Statement in java.awt paint

    import java.applet.Applet;  //bring in the applet class
    import java.awt.*;             //bring in the graphics class
    import java.awt.event.*;      //bring in the event class
    import java.text.DecimalFormat;    //bring in the decimal format class
    import java.lang.Float;       //bring in the float class
    public class Bmi extends Applet implements ActionListener {   //begin program and start ActionListener
      Label weight, height;    //define Label variable
      TextField weighttext, heighttext;    //define TextField variables
      Button calculate;     //define button variables
      float index, wt, ht, max, min;    //define float variables
      DecimalFormat fmt2 = new DecimalFormat("#.00"); //set decimal format for reals
    public void init() {    //begin init()
      weight = new Label("Please enter your weight in Kg. (2 decimal places): ");   //define content of Label weight
      weighttext = new TextField(6);            //define size of TextField
      height = new Label("Please enter your height in Metres (2 decimal places): ");   //define content of Label height
      heighttext = new TextField(5);    //define size of TextField
      calculate = new Button("Calculate!!");       //define content of Button
      add(weight);      //add Label weight to the GUI
      add(weighttext);   //add TextField weighttext to the GUI
      add(height);      //add Label height to the GUI
      add(heighttext);     //add TextField heighttext to the GUI
      add(calculate);        //add button calculate to the GUI
      calculate.addActionListener(this);    //wait for button to be returned
      wt = 0;     //reset wt to 0
      index = 0;  //reset index to 0
      ht = 0;      //reset ht to 0
      max = 0;      //reset max to 0
      min = 0;    //reset min to 0
      public void actionPerformed( ActionEvent e ) {   //run upon return of button
      wt = Float.parseFloat(weighttext.getText());  //convert weighttext from String to Float
      ht = Float.parseFloat(heighttext.getText());    //covert heighttext from String to Float
      repaint();     //refresh paint area
      public float indexer()  //begin indexer method
        float ind;    //delare local variable ind
        ind = wt/(ht*ht);      //perform calculation
        return ind;    //make indexer() the value of variable ind
      }  // end of indexer method
      public float maxWeight()  //begin maxWeight method
        float maxwt;    //declare local variable maxwt
        final float UPPER = 25.0f;   //declare variable UPPER as a float with a decimal value of 25.0
        maxwt = UPPER*ht*ht;      //perform calculation
        return maxwt;          //make maxWeight() the value of variable maxwt
      }  // end of maxWeight method
      public float minWeight()   //begin minWeight method
        float minwt;    //declare local variable minwt
        final float LOWER= 20.0f;   //declare variable LOWER as a float with a decimal value of 20.0
        minwt = LOWER*ht*ht;    //perform calculation
        return minwt;      //make minWeight() the value of variable minwt
      }  // end of minWeight method
    public void paint(Graphics g)    //begin paint method, define g as Graphics
        index=indexer();   //covert method indexer() to variable index
        max=maxWeight();      //convert method maxWeight() to variable max
        min=minWeight();     //convert method minWeight() to variable min
        g.setFont(new Font("Verdana", Font.ITALIC, 15));    //define font, weight and size
        g.setColor(new Color(90,90,90));     //set new colour
        g.drawRect(5,100,300,75);      //define size of rectangle
        g.setColor(new Color(255,107,9));   //set new colour
        g.drawString("BMI is " + fmt2.format(index) + " for " + fmt2.format(wt) + "kg",20,120);   //create string in paint, define its on screen position
        g.drawString("Maximum bodyweight is " + fmt2.format(max) + "kg", 20,140);   //create string in paint, define its on screen position
        g.drawString("Minimum bodyweight is " + fmt2.format(min) + "kg", 20,160);     //create string in paint, define its on screen position
      }  // end of paint method
    }    // end of Bmi classI have written the above code to calculate someones BMI (Body Mass Index). Basically as you can see it recieves a weight and height from the user and calculates the rest. But whilst that good I would like to know how I can make it tell the user something to the effect of "Your overweight" or "Your underweight". The if statement runs like this:
    if (wt > max)This forum doesn't quite handle <> properly. The greater and less than symbols. So above you will see > this is the html character code for a greater than symbol so please read it as such.
    And then if wt is greater than max then it will say "Your overweight".
    But I can't figure out how to include it in the above program. Becuase it won't run in paint, atleast it won't the way I have done it previously. So can you think of any other ways?
    Help much appreciated,
    Simon

    Thanks very much that works well.
    Simon
    My code now looks like this: import java.applet.Applet;  //bring in the applet class
    import java.awt.*;             //bring in the graphics class
    import java.awt.event.*;      //bring in the event class
    import java.text.DecimalFormat;    //bring in the decimal format class
    import java.lang.Float;       //bring in the float class
    public class Bmi extends Applet implements ActionListener {   //begin program and start ActionListener
      Label weight, height;    //define Label variable
      TextField weighttext, heighttext;    //define TextField variables
      Button calculate;     //define button variables
      float index, wt, ht, max, min;    //define float variables
      DecimalFormat fmt2 = new DecimalFormat("#.00"); //set decimal format for reals
    public void init() {    //begin init()
      weight = new Label("Please enter your weight in Kg. (2 decimal places): ");   //define content of Label weight
      weighttext = new TextField(6);            //define size of TextField
      height = new Label("Please enter your height in Metres (2 decimal places): ");   //define content of Label height
      heighttext = new TextField(5);    //define size of TextField
      calculate = new Button("Calculate!!");       //define content of Button
      add(weight);      //add Label weight to the GUI
      add(weighttext);   //add TextField weighttext to the GUI
      add(height);      //add Label height to the GUI
      add(heighttext);     //add TextField heighttext to the GUI
      add(calculate);        //add button calculate to the GUI
      calculate.addActionListener(this);    //wait for button to be returned
      wt = 0;     //reset wt to 0
      index = 0;  //reset index to 0
      ht = 0;      //reset ht to 0
      max = 0;      //reset max to 0
      min = 0;    //reset min to 0
      public void actionPerformed( ActionEvent e ) {   //run upon return of button
      wt = Float.parseFloat(weighttext.getText());  //convert weighttext from String to Float
      ht = Float.parseFloat(heighttext.getText());    //covert heighttext from String to Float
      repaint();     //refresh paint area
      public float indexer()  //begin indexer method
        float ind;    //delare local variable ind
        ind = wt/(ht*ht);      //perform calculation
        return ind;    //make indexer() the value of variable ind
      }  // end of indexer method
      public float maxWeight()  //begin maxWeight method
        float maxwt;    //declare local variable maxwt
        final float UPPER = 25.0f;   //declare variable UPPER as a float with a decimal value of 25.0
        maxwt = UPPER*ht*ht;      //perform calculation
        return maxwt;          //make maxWeight() the value of variable maxwt
      }  // end of maxWeight method
      public float minWeight()   //begin minWeight method
        float minwt;    //declare local variable minwt
        final float LOWER= 20.0f;   //declare variable LOWER as a float with a decimal value of 20.0
        minwt = LOWER*ht*ht;    //perform calculation
        return minwt;      //make minWeight() the value of variable minwt
      }  // end of minWeight method
    public void you(Graphics g)
      String statement;
      if(wt > max) statement="You are very fat";
      else if(wt < min) statement="You are very thin";
      else statement="You are in the recommended weight range for your height";
      g.drawString(statement, 20,210);
    public void paint(Graphics g)    //begin paint method, define g as Graphics
        you(g);
        index=indexer();   //covert method indexer() to variable index
        max=maxWeight();      //convert method maxWeight() to variable max
        min=minWeight();     //convert method minWeight() to variable min
        g.setFont(new Font("Verdana", Font.ITALIC, 15));    //define font, weight and size
        g.setColor(new Color(90,90,90));     //set new colour
        g.drawRect(5,100,300,75);      //define size of rectangle
        g.setColor(new Color(255,107,9));   //set new colour
        g.drawString("BMI is " + fmt2.format(index) + " for " + fmt2.format(wt) + "kg",20,120);   //create string in paint, define its on screen position
        g.drawString("Maximum bodyweight is " + fmt2.format(max) + "kg", 20,140);   //create string in paint, define its on screen position
        g.drawString("Minimum bodyweight is " + fmt2.format(min) + "kg", 20,160);     //create string in paint, define its on screen position
      }  // end of paint method
    }    // end of BmiThanks again,
    Simon

  • Custom graphics in java.awt.ScrollPane

    Hi all,
    I have to draw a custom created image in a scroll pane. As the image is very large I want to display it in a scroll pane. As parts of the image may change within seconds, and drawing the whole image is very time consuming (several seconds) I want to draw only the part of the image that is currently visible to the user.
    My idea: creating a new class that extends from java.awt.ScrollPane, overwrite the paint(Graphics) method and do the drawings inside. Unfortunately, it does not work. The background of the scoll pane is blue, but it does not show the red box (the current viewport is not shown in red).
    Below please find the source code that I am using:
    package graphics;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.ScrollPane;
    import java.awt.event.AdjustmentEvent;
    public class CMyComponent extends ScrollPane {
         /** <p>Listener to force a component to repaint when a scroll bar changes its
          * position.</p>
         private final class ScrollBarAdjustmentListener implements java.awt.event.AdjustmentListener {
              /** <p>The component to force to repaint.</p> */
              private final Component m_Target;
              /** <p>Default constructor.</p>
               * @param Target The component to force to repaint.
              private ScrollBarAdjustmentListener(Component Target) { m_Target = Target; }
              /** <p>Forces to component to repaint upon adjustment of the scroll bar.</p>
               *  @see java.awt.event.AdjustmentListener#adjustmentValueChanged(java.awt.event.AdjustmentEvent)
              public void adjustmentValueChanged(AdjustmentEvent e) { m_Target.paint(m_Target.getGraphics()); }
         public CMyComponent() {
              // Ensure that the component repaints upon changing of the scroll bars
              ScrollBarAdjustmentListener sbal = new ScrollBarAdjustmentListener(this);
              getHAdjustable().addAdjustmentListener(sbal);
              getVAdjustable().addAdjustmentListener(sbal);
         public void paint(Graphics g) {
              setBackground(Color.BLUE);
              g.setColor(Color.RED);
              g.fillRect(getScrollPosition().x, getScrollPosition().y, getViewportSize().width, getViewportSize().height);
         public final static void main(String[] args) {
              java.awt.Frame f = new java.awt.Frame();
              f.add(new CMyComponent());
              f.pack();
              f.setVisible(true);
    }

    Dear all,
    I used the last days and tried several things. I think now I have a quite good working solution (just one bug remains) and it is very performant. To give others a chance to see what I have done I post the source code of the main class (a canvas drawing and implementing scrolling) here. As soon as the sourceforge project is accepted, I will publish the whole sources at there. Enjoy. And if you have some idea for my last bug in getElementAtPixel(Point), then please tell me.
    package internetrail.graphics.hexgrid;
    import java.awt.Canvas;
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Image;
    import java.awt.Point;
    import java.awt.Polygon;
    import java.awt.event.ComponentEvent;
    import java.awt.event.ComponentListener;
    import java.awt.geom.Area;
    import java.awt.image.BufferedImage;
    import java.util.WeakHashMap;
    import java.util.Map;
    /** <p>Hex grid view.</p>
    * <p>Visualizes a {@link IHexGridModel}.</p>
    * @version 0.1, 03.06.2006
    * @author Bjoern Wuest, Germany
    public final class CHexGridView extends Canvas implements ComponentListener, IHexGridElementListener {
         /** <p>Serial version unique identifier.</p> */
         private static final long serialVersionUID = -965902826101261530L;
         /** <p>Instance-constant parameter for the width of a hex grid element.</p> */
         public final int CONST_Width;
         /** <p>Instance-constant parameter for 1/4 of the width of a hex grid element.</p> */
         public final int CONST_Width1fourth;
         /** <p>Instance-constant parameter for 3/4 of the width of a hex grid element.</p> */
         public final int CONST_Width3fourth;
         /** <p>Instance-constant parameter for 1.5 times of the width of a hex grid element.</p> */
         public final int CONST_Width1dot5;
         /** <p>Instance-constant parameter for 4 times of the width of a hex grid element.</p> */
         public final int CONST_Widthquad;
         /** <p>Instance-constant parameter for the height of a hex grid element.</p> */
         public final int CONST_Height;
         /** <p>Instance-constant parameter for 1/2 of the height of a hex grid element.</p> */
         public final int CONST_Heighthalf;
         /** <p>Instance-constant parameter for the double height of a hex grid element.</p> */
         public final int CONST_Heightdouble;
         /** <p>The steepness of a side of the hex grid element (calculated for the upper left arc).</p> */
         public final double CONST_Steepness;
         /** <p>The model of this hex grid </p> */
         private final IHexGridModel m_Model;
         /** <p>A cache for already created images of the hex map.</p> */
         private final Map<Point, Image> m_Cache = new WeakHashMap<Point, Image>();
         /** <p>The graphical area to draw the selection ring around a hex element.</p> */
         private final Area m_SelectionRing;
         /** <p>The image of the selection ring around a hex element.</p> */
         private final BufferedImage m_SelectionRingImage;
         /** <p>The current position of the hex grid in pixels (top left visible corner).</p> */
         private Point m_ScrollPosition = new Point(0, 0);
         /** <p>Flag to define if a grid is shown ({@code true}) or not ({@code false}).</p> */
         private boolean m_ShowGrid = true;
         /** <p>Flag to define if the selected hex grid element should be highlighted ({@code true}) or not ({@code false}).</p> */
         private boolean m_ShowSelected = true;
         /** <p>The offset of hex grid elements shown on the screen, measured in hex grid elements.</p> */
         private Point m_CurrentOffset = new Point(0, 0);
         /** <p>The offset of the image shown on the screen, measured in pixels.</p> */
         private Point m_PixelOffset = new Point(0, 0);
         /** <p>The index of the currently selected hex grid element.</p> */
         private Point m_CurrentSelected = new Point(0, 0);
         /** <p>The width of a buffered pre-calculated image in pixel.</p> */
         private int m_ImageWidth;
         /** <p>The height of a buffered pre-calculated image in pixel.</p> */
         private int m_ImageHeight;
         /** <p>The maximum number of columns of hex grid elements to be shown at once on the screen.</p> */
         private int m_MaxColumn;
         /** <p>The maximum number of rows of hex grid elements to be shown at once on the screen.</p> */
         private int m_MaxRow;
         /** <p>Create a new hex grid view.</p>
          * <p>The hex grid view is bound to a {@link IHexGridModel} and registers at
          * that model to listen for {@link IHexGridElement} updates.</p>
          * @param Model The model backing this view.
         public CHexGridView(IHexGridModel Model) {
              // Set the model
              m_Model = Model;
              CONST_Width = m_Model.getElementsWidth();
              CONST_Height = m_Model.getElementsHeight();
              CONST_Width1fourth = CONST_Width/4;
              CONST_Width3fourth = CONST_Width*3/4;
              CONST_Width1dot5 = CONST_Width*3/2;
              CONST_Heighthalf = CONST_Height/2;
              CONST_Widthquad = CONST_Width*4;
              CONST_Heightdouble = CONST_Height*2;
              CONST_Steepness = (double)CONST_Heighthalf / CONST_Width1fourth;
              m_ImageWidth = getSize().width+CONST_Widthquad;
              m_ImageHeight = getSize().height+CONST_Heightdouble;
              m_MaxColumn = m_ImageWidth / CONST_Width3fourth;
              m_MaxRow = m_ImageHeight / CONST_Height;
              // Register this canvas for various notifications
              m_Model.addElementListener(this);
              addComponentListener(this);
              // Create the selection ring to highlight hex grid elements
              m_SelectionRing = new Area(new Polygon(new int[]{-1, CONST_Width1fourth-1, CONST_Width3fourth+1, CONST_Width+1, CONST_Width3fourth+1, CONST_Width1fourth-1}, new int[]{CONST_Heighthalf, -1, -1, CONST_Heighthalf, CONST_Height+1, CONST_Height+1}, 6));
              m_SelectionRing.subtract(new Area(new Polygon(new int[]{2, CONST_Width1fourth+2, CONST_Width3fourth-2, CONST_Width-2, CONST_Width3fourth-2, CONST_Width1fourth+2}, new int[]{CONST_Heighthalf, 2, 2, CONST_Heighthalf, CONST_Height-2, CONST_Height-2}, 6)));
              m_SelectionRingImage = new BufferedImage(CONST_Width, CONST_Height, BufferedImage.TYPE_INT_ARGB);
              Graphics2D g = m_SelectionRingImage.createGraphics();
              g.setColor(Color.WHITE);
              g.fill(m_SelectionRing);
         @Override public synchronized void paint(Graphics g2) {
              // Caculate the offset of indexes to show
              int offsetX = 2 * (m_ScrollPosition.x / CONST_Width1dot5) - 2;
              int offsetY = (int)(Math.ceil(m_ScrollPosition.y / CONST_Height) - 1);
              m_CurrentOffset = new Point(offsetX, offsetY);
              // Check if the image is in the cache
              Image drawing = m_Cache.get(m_CurrentOffset);
              if (drawing == null) {
                   // The image is not cached, so draw it
                   drawing = new BufferedImage(m_ImageWidth, m_ImageHeight, BufferedImage.TYPE_INT_ARGB);
                   Graphics2D g = ((BufferedImage)drawing).createGraphics();
                   // Draw background
                   g.setColor(Color.BLACK);
                   g.fillRect(0, 0, m_ImageWidth, m_ImageHeight);
                   // Draw the hex grid
                   for (int column = 0; column <= m_MaxColumn; column += 2) {
                        for (int row = 0; row <= m_MaxRow; row++) {
                             // Draw even column
                             IHexGridElement element = m_Model.getElementAt(offsetX + column, offsetY + row);
                             if (element != null) { g.drawImage(element.getImage(m_ShowGrid), (int)(column*(CONST_Width3fourth-0.5)), CONST_Height*row, null); }
                             // Draw odd column
                             element = m_Model.getElementAt(offsetX + column+1, offsetY + row);
                             if (element!= null) { g.drawImage(element.getImage(m_ShowGrid), (int)(column*(CONST_Width3fourth-0.5)+CONST_Width3fourth), CONST_Heighthalf*(row*2+1), null); }
                   // Put the image into the cache
                   m_Cache.put(m_CurrentOffset, drawing);
              // Calculate the position of the image to show
              offsetX = CONST_Width1dot5 + (m_ScrollPosition.x % CONST_Width1dot5);
              offsetY = CONST_Height + (m_ScrollPosition.y % CONST_Height);
              m_PixelOffset = new Point(offsetX, offsetY);
              g2.drawImage(drawing, -offsetX, -offsetY, null);
              // If the selected element should he highlighted, then do so
              if (m_ShowSelected) {
                   // Check if the selected element is on screen
                   if (isElementOnScreen(m_CurrentSelected)) {
                        // Correct vertical offset for odd columns
                        if ((m_CurrentSelected.x % 2 == 1)) { offsetY -= CONST_Heighthalf; }
                        // Draw the selection circle
                        g2.drawImage(m_SelectionRingImage, (m_CurrentSelected.x - m_CurrentOffset.x) * CONST_Width3fourth - offsetX - ((m_CurrentSelected.x + 1) / 2), (m_CurrentSelected.y - m_CurrentOffset.y) * CONST_Height - offsetY, null);
         @Override public synchronized void update(Graphics g) { paint(g); }
         public synchronized void componentResized(ComponentEvent e) {
              // Upon resizing of the component, adjust several pre-calculated values
              m_ImageWidth = getSize().width+CONST_Widthquad;
              m_ImageHeight = getSize().height+CONST_Heightdouble;
              m_MaxColumn = m_ImageWidth / CONST_Width3fourth;
              m_MaxRow = m_ImageHeight / CONST_Height;
              // And flush the cache
              m_Cache.clear();
         public void componentMoved(ComponentEvent e) { /* do nothing */ }
         public void componentShown(ComponentEvent e) { /* do nothing */ }
         public void componentHidden(ComponentEvent e) { /* do nothing */ }
         public synchronized void elementUpdated(IHexGridElement Element) {
              // Clear cache where the element may be contained at
              for (Point p : m_Cache.keySet()) { if (isElementInScope(Element.getIndex(), p, new Point(p.x + m_MaxColumn, p.y + m_MaxRow))) { m_Cache.remove(p); } }
              // Update the currently shown image if the update element is shown, too
              if (isElementOnScreen(Element.getIndex())) { repaint(); }
         /** <p>Returns the model visualized by this grid view.</p>
          * @return The model visualized by this grid view.
         public IHexGridModel getModel() { return m_Model; }
         /** <p>Returns the current selected hex grid element.</p>
          * @return The current selected hex grid element.
         public IHexGridElement getSelected() { return m_Model.getElementAt(m_CurrentSelected.x, m_CurrentSelected.y); }
         /** <p>Sets the current selected hex grid element by its index.</p>
          * <p>If the selected hex grid element should be highlighted and is currently
          * shown on the screen, then this method will {@link #repaint() redraw} this
          * component automatically.</p>
          * @param Index The index of the hex grid element to become the selected one.
          * @throws IllegalArgumentException If the index refers to a non-existing hex
          * grid element.
         public synchronized void setSelected(Point Index) throws IllegalArgumentException {
              // Check that the index is valid
              if ((Index.x < 0) || (Index.y < 0) || (Index.x > m_Model.getXElements()) || (Index.y > m_Model.getYElements())) { throw new IllegalArgumentException("There is no hex grid element with such index."); }
              m_CurrentSelected = Index;
              // If the element is on screen and should be highlighted, then repaint
              if (m_ShowSelected && isElementOnScreen(m_CurrentSelected)) { repaint(); }
         /** <p>Moves the visible elements to the left by the number of pixels.</p>
          * <p>To move the visible elements to the left by one hex grid element, pass
          * {@link #CONST_Width3fourth} as the parameter. The component will
          * automatically {@link #repaint()}.</p>
          * @param Pixels The number of pixels to move to the left.
          * @return The number of pixels moved to the left. This is always between 0
          * and {@code abs(Pixels)}.
         public synchronized int moveLeft(int Pixels) {
              int delta = m_ScrollPosition.x - Math.max(0, m_ScrollPosition.x - Math.max(0, Pixels));
              if (delta != 0) {
                   m_ScrollPosition.x -= delta;
                   repaint();
              return delta;
         /** <p>Moves the visible elements up by the number of pixels.</p>
          * <p>To move the visible elements up by one hex grid element, pass {@link
          * #CONST_Height} as the parameter. The component will automatically {@link
          * #repaint()}.</p>
          * @param Pixels The number of pixels to move up.
          * @return The number of pixels moved up. This is always between 0 and {@code
          * abs(Pixels)}.
         public synchronized int moveUp(int Pixels) {
              int delta = m_ScrollPosition.y - Math.max(0, m_ScrollPosition.y - Math.max(0, Pixels));
              if (delta != 0) {
                   m_ScrollPosition.y -= delta;
                   repaint();
              return delta;
         /** <p>Moves the visible elements to the right by the number of pixels.</p>
          * <p>To move the visible elements to the right by one hex grid element, pass
          * {@link #CONST_Width3fourth} as the parameter. The component will
          * automatically {@link #repaint()}.</p>
          * @param Pixels The number of pixels to move to the right.
          * @return The number of pixels moved to the right. This is always between 0
          * and {@code abs(Pixels)}.
         public synchronized int moveRight(int Pixels) {
              int delta = Math.min(m_Model.getXElements() * CONST_Width3fourth + CONST_Width1fourth - getSize().width, m_ScrollPosition.x + Math.max(0, Pixels)) - m_ScrollPosition.x;
              if (delta != 0) {
                   m_ScrollPosition.x += delta;
                   repaint();
              return delta;
         /** <p>Moves the visible elements down by the number of pixels.</p>
          * <p>To move the visible elements down by one hex grid element, pass {@link
          * #CONST_Height} as the parameter. The component will automatically {@link
          * #repaint()}.</p>
          * @param Pixels The number of pixels to move down.
          * @return The number of pixels moved down. This is always between 0 and
          * {@code abs(Pixels)}.
         public synchronized int moveDown(int Pixels) {
              int delta = Math.min(m_Model.getYElements() * CONST_Height + CONST_Heighthalf - getSize().height, m_ScrollPosition.y + Math.max(0, Pixels)) - m_ScrollPosition.y;
              if (delta != 0) {
                   m_ScrollPosition.y += delta;
                   repaint();
              return delta;
         /** <p>Checks if the hex grid element of the given index is currently
          * displayed on the screen (even just one pixel).</p>
          * <p>The intention of this method is to check if a {@link #repaint()} is
          * necessary or not.</p>
          * @param ElementIndex The index of the element to check.
          * @return {@code true} if the hex grid element of the given index is
          * displayed on the screen, {@code false} if not.
         public synchronized boolean isElementOnScreen(Point ElementIndex) { return isElementInScope(ElementIndex, m_CurrentOffset, new Point(m_CurrentOffset.x + m_MaxColumn, m_CurrentOffset.y + m_MaxRow)); }
         /** <p>Checks if the hex grid element of the given index is within the given
          * indexes.</p>
          * <p>The intention of this method is to check if a {@link #repaint()} is
          * necessary or not.</p>
          * @param ElementIndex The index of the element to check.
          * @param ReferenceIndexLeftTop The left top index of the area to check.
          * @param ReferenceIndexRightBottom The right bottom index of the area to check.
          * @return {@code true} if the hex grid element of the given index is within
          * the given area, {@code false} if not.
         public synchronized boolean isElementInScope(Point ElementIndex, Point ReferenceIndexLeftTop, Point ReferenceIndexRightBottom) { if ((ElementIndex.x >= ReferenceIndexLeftTop.x) && (ElementIndex.x <= ReferenceIndexRightBottom.x) && (ElementIndex.y >= ReferenceIndexLeftTop.y) && (ElementIndex.y <= (ReferenceIndexRightBottom.y))) { return true; } else { return false; } }
         /** <p>Return the {@link IHexGridElement hex grid element} shown at the given
          * pixel on the screen.</p>
          * <p><b>Remark: There seems to be a bug in retrieving the proper element,
          * propably caused by rounding errors and unprecise pixel calculations.</p>
          * @param P The pixel on the screen.
          * @return The {@link IHexGridElement hex grid element} shown at the pixel.
         public synchronized IHexGridElement getElementAtPixel(Point P) {
              // @FIXME Here seems to be some bugs remaining
              int dummy = 0; // Variable for warning to indicate that there is something to do :)
              // Calculate the pixel on the image, not on the screen
              int px = P.x + m_PixelOffset.x;
              int py = P.y + m_PixelOffset.y;
              // Determine the x-index of the column (is maybe decreased by one)
              int x = px / CONST_Width3fourth + m_CurrentOffset.x;
              // If the column is odd, then shift the y-pixel by half element height
              if ((x % 2) == 1) { py -= CONST_Heighthalf; }
              // Determine the y-index of the row (is maybe decreased by one)
              int y = py / CONST_Height + m_CurrentOffset.y;
              // Normative coordinates to a single element
              px -= (x - m_CurrentOffset.x) * CONST_Width3fourth;
              py -= (y - m_CurrentOffset.y) * CONST_Height;
              // Check if the normative pixel is in the first quarter of a column
              if (px < CONST_Width1fourth) {
                   // Adjustments to the index may be necessary
                   if (py < CONST_Heighthalf) {
                        // We are in the upper half of a hex-element
                        double ty = CONST_Heighthalf - CONST_Steepness * px;
                        if (py < ty) { x--; }
                   } else {
                        // We are in the lower half of a hex-element
                        double ty = CONST_Heighthalf + CONST_Steepness * px;
                        if (py > ty) {
                             x--;
                             y++;
              return m_Model.getElementAt(x, y);
    }Ah, just to give you some idea: I use this component to visualize a hex grid map with more than 1 million grid elements. And it works, really fast, and requires less than 10 MByte of memory.

  • Problems changing colour using Graphics class in java.awt

    Hi,
    The problem only happens when more than two images are on a panel. In this case, I have to strings that are drawn. The first drawn string is called "A" the second drawn string is called "B". However, when i change the colour of "B" to let's say Red, the panel erases the letter "B" and insteads changes "A" to red. How can I fix this so that when the user chooses the colour red it changes the colour of the latest drawn string and not the first one. please help!!!!
    import java.awt.*;
    public class StringPanel extends GBPanel
         private String shape = "clear", str;
         private int x, y;
         private Color color = Color.black;
         public void paintComponent(Graphics g)
              super.paintComponent(g);
              g.setColor (color);
              if(shape.equalsIgnoreCase("draw string"))
                   g.setColor(color);
                   g.drawString(str, x, y);
              else if (shape.equalsIgnoreCase("exit"))
                   System.exit(0);
         public void drawCurve(Color color)
         this.color = color;
         repaint();
         public void drawString(String shape, String str, int x, int y)
              this.shape = shape;
              this.str = str;
              this.x = x;
              this.y = y;
              repaint();
         public void drawString1(String shape, String str, int x, int y)
              Graphics g = getGraphics();
              g.setColor(color);
              if (shape.equalsIgnoreCase("draw string"))
                   g.setColor(color);
                   g.drawString(str, x, y);
              else
                   repaint();
    }

    well, as I said, I can't remember what the update method thing was for... I think it was related to not clearing the screen first.
    Anyway, if you maintain a list of objects that should be drawn and then in the paintComponent method, loop thru the list of objects and redraw them, it will work. Then you change the state of an object and call repaint. When you are going to change color, you need to, in effect, redraw the entire affected area. Now this can be done partially with clipping, but it's complicated to deal with that. So the simplest way is just redraw everything on repaint.

  • How to repaint a portion of a component?

    I am working with JLayeredPane and several overlapping components which I draw a selection rectangle around when the user clicks on a component to indicate that it is "selected". If the user selects another component I need to wipe out the selection rectangle on the previously selected component. I'm not sure what the best approach for this is.
    If the initially selected component was underneath (in a lower layer than) another component, I can't simply repaint it without repainting all of the components that are above it. This seems like it could be too much painting just to remove a selection box. Can someone recommend a good approach for this problem?
    Thanks,
    Jonathan

    Thanks for the response. The components should be on separate layers (added via JLayeredPane.add(JComponent) ) so if the painter takes the layers into account, then there must be something else wrong. Here's a quick demo program of what I'm doing:
    import java.awt.*;
    import java.awt.event.MouseEvent;
    import javax.swing.*;
    import javax.swing.event.MouseInputAdapter;
    public class LayerDemo {
         private ControlMouseInputAdapter controlMouseInputAdapter = new ControlMouseInputAdapter();
    private static void createAndShowGUI() {
         LayerDemo layerDemo = new LayerDemo();
    JFrame mainFrame = new JFrame();
    try {
    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {;}
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    mainFrame.setSize(400, 400);
    JLayeredPane layeredPane = mainFrame.getLayeredPane();
    layeredPane.add(layerDemo.createColoredLabel("test1", Color.RED, new Point(20, 20)));
    layeredPane.add(layerDemo.createColoredLabel("test2", Color.BLUE, new Point(40, 40)));
    mainFrame.setVisible(true);
    private JLabel createColoredLabel(String text, Color color,
    Point origin) {
    JLabel label = new JLabel();
    label.addMouseListener(controlMouseInputAdapter);
    label.setText(text);
    label.setOpaque(true);
    label.setBackground(color);
    label.setBounds(origin.x, origin.y, 140, 140);
    return label;
    public static void main(String[] args) throws Exception {
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {createAndShowGUI();}
    private class ControlMouseInputAdapter extends MouseInputAdapter {
    public void mouseEntered(MouseEvent e) {
    JComponent component = (JComponent) e.getSource();
    component.setBorder(BorderFactory.createLineBorder(Color.black));
    public void mouseExited(MouseEvent e) {
    JComponent component = (JComponent) e.getSource();
    component.setBorder(null);
    }

  • How to repaint a component when it moves?

    Hello, I have an application with many JPanels packed together, and one of them has a picture that I render with the paint() method, using the coordinates of the panel as reference. For example, suppose I were to draw the diagonal:
    Dimension d = getSize();
    int w = d.width;
    int h = d.height;
    g.clearRect(0, 0, w, h);
    g.drawLine(0, 0, d.width - 1, d.height - 1);Now on events of user input, the size of other components may change and I revalidate the root pane. This may move or resize my JPanel where I drew.
    So I thought paint() would automatically be called if the component is moved. But it's not! the JPanel moves around, with the diagonal staying in its old place on the screen (so it is no longer the diagonal of the moved JPanel).
    Why and How to do this properly?      It would not be easy, if the user changes any of the many components, to have to manually keep track of everything else and repaint() everything else on the account that it might move, or have to compute whether it moved and repaint(). Wouldn't I be doing the job of the layout manager then? (I use many nested GridBag Layout managers).
    Thank you for any insight. Mark

    For example:
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.awt.image.BufferedImage;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.net.URL;
    import javax.imageio.ImageIO;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JComponent;
    * @version 1.0, 11/13/2008
    * @author Pete
    * Image from Funny Junk website: http://www.funnyjunk.com/funny_pictures/
    public class MovePicPanel
      private static final Dimension PANEL_SIZE = new Dimension(800, 700);
      private JPanel mainPanel = new JPanel();
      private BufferedImage image;
      private JPanel picPanel = new JPanel()
        protected void paintComponent(Graphics g)
          super.paintComponent(g);
          if (image != null)
            //!! here's where I draw my image in the JPanel
            g.drawImage(image, 0, 0, this);
      public MovePicPanel()
        try
          image  = ImageIO.read(new URL("http://newmedia.funnyjunk.com/pictures/bills-in-context.jpg"));
        catch (MalformedURLException e)
          e.printStackTrace();
        catch (IOException e)
          e.printStackTrace();
        if (image != null)
          int width = image.getWidth();
          int height = image.getHeight();
          picPanel.setSize(new Dimension(width, height));
          picPanel.setLocation(0, 0);
        JLabel clickMeLabel = new JLabel("Click me and drag mouse");
        clickMeLabel.setFont(clickMeLabel.getFont().deriveFont(Font.BOLD, 32));
        clickMeLabel.setForeground(Color.red);
        picPanel.add(clickMeLabel);
        MouseAdapter mouseAdapter = new MyMouseAdapter();
        mainPanel.addMouseListener(mouseAdapter);
        mainPanel.addMouseMotionListener(mouseAdapter);
        mainPanel.setPreferredSize(PANEL_SIZE);
        mainPanel.setLayout(null);
        mainPanel.add(picPanel);
      public JComponent getComponent()
        return mainPanel;
      private class MyMouseAdapter extends MouseAdapter
        @Override
        public void mousePressed(MouseEvent e)
          picPanel.setLocation(e.getPoint());
        @Override
        public void mouseDragged(MouseEvent e)
          picPanel.setLocation(e.getPoint());
      private static void createAndShowUI()
        JFrame frame = new JFrame("MovePicPanel");
        frame.getContentPane().add(new MovePicPanel().getComponent());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
      public static void main(String[] args)
        java.awt.EventQueue.invokeLater(new Runnable()
          public void run()
            createAndShowUI();
    }

  • How to repaint a panel

    Hi All!
    I am trying to display a few textFields in an AWT applet. The number of textFields I need to set is variable. I want to repaint a portion of an applet (the panel in which these textFields are placed) when a button is clicked.
    In the code below, I added a textField array in panel 1(p1), initialized with record size (no_of_rec), which I know at the beginning (no_of_rec = 2 at INDEX = 0).
    When I click "Next Item" button, I want to show 4 textFields (no_of_rec = 4 at INDEX = 1), with the values C, D, E, F.
    One more click (INDEX = 2) should show one textField only, with the value X.
    The codes for the textFields are in a method(addDataPanel), so that I can call it when I click "Next Item" button. A system.out check shows that 4 textFields are created when INDEX = 1, and so on, but with calling repaint() inside the button's actionPerformed method, I am unable to update the panel (p1) dynamically.
    When I minimize the window with [-] button, and get back to the original size, I can see the no of textFields have increased to 6; 2 from the beginning and 4 from the first click.
    Could someone please help?
    Thank you.
    Tienshan
    Here is my code:
    import java.awt.*;                           
    import java.applet.*;                       
    import java.awt.event.*;
    public class test1020 extends Applet{
         int NO_OF_REC = 0;
         int INDEX = 0;
         TextField[] txtDataRowDisplay;
         String[] data;
         Panel p1;
         GridBagConstraints c1;
         Color pnlBgColor = new Color(144, 196, 222);
         public void init() {     
              data = getData(INDEX);
              NO_OF_REC = data.length;
              //main Panel
              Panel pMain = new Panel();
              pMain.setLayout(new GridBagLayout());
              GridBagConstraints c  = new GridBagConstraints();
              pMain.setBackground(pnlBgColor);
              //p0
              Panel p0 = new Panel();
              p0.setLayout(new GridBagLayout());
              GridBagConstraints c0  = new GridBagConstraints();
              c0.fill = GridBagConstraints.HORIZONTAL;
              p0.setBackground(pnlBgColor);
              //p1
              p1 = new Panel();
              p1.setLayout(new GridBagLayout());
              c1  = new GridBagConstraints();
              Button btnNext = new Button("Next Item");
              c0.insets = new Insets(0, 0, 10, 0);
              c0.gridx = 3;
              c0.gridy = 0;
              p0.add(btnNext, c0);
              btnNext.addActionListener(
                   new ActionListener() {
                        public void actionPerformed(ActionEvent e){
                             INDEX++;     
                             data = getData(INDEX);
                             NO_OF_REC = data.length;
                             addDataPanel(p1, c1);
                             display(data);
                             p1.repaint();
              //call a method to add data row(s)
              addDataPanel(p1, c1);
              //add p0 and p1 to pMain;
              c.gridx = 0;
              c.gridy = 0;
              pMain.add(p0, c);
              c.gridx = 0;
              c.gridy = 1;
              pMain.add(p1, c);
              add(pMain);
              this.setBackground(pnlBgColor);
              display(data);
         }//init
         private String[] getData(int index){
              if(index == 0){
                   String[] names = { "A", "B" };
                   return names;
              else if (index==1) {
                   String[] names = { "C", "D", "E", "F" };
                   return names;
              else {
                   String[] names = { "X" };
                   return names;
        private void addDataPanel(Panel p1, GridBagConstraints c1){
              txtDataRowDisplay = new TextField[NO_OF_REC];
              for(int i = 0; i < NO_OF_REC; i++){
                   txtDataRowDisplay[i] = new TextField(4);
              int cnt = 0;
              for(int m = 0; m < txtDataRowDisplay.length; m++ ){
                   c1.gridx = 0;
                   c1.gridy = m + cnt;
                   p1.add(txtDataRowDisplay[m], c1);
                   cnt++;
         private void display(String[] data){
              for(int i = 0; i < data.length; i++){
                   txtDataRowDisplay.setText(data[i]);

    BickelT , yes, it does work! I am almost there, only a small hurdle. When I initialize my textFields with a bigger size, all the smaller sizes are painted correctly. But when the initial size (when index is 0, that is at the time of init) is small, all the subsequent sizes are fixed to that init size.
    For example, when I change my code to the following, it works fine.
    private String[] getData(int index){
              if(index == 0){
                   String[] names = { "C", "D", "E", "F" };
                   return names;
              else if (index==1) {
                   String[] names = { "A", "B" };
                   return names;
              else {
                   String[] names = { "X"};
                   return names;
         } With the code as it is (as posted originally), in the first click, a textField with space(=height) for two textFields is painted with the value C and the lower half is empty. It is refusing to draw the area bigger than the init size of 2. When I resize the applet, I can see that four textFields with the values C, D, E, F.have been painted.
    I added the codes you suggested inside the addActionListner class. Isn't that the correct place to add the codes?
    BTW, with or without p1.repaint, the result is the same.
    What could have gone wrong?
    Thank you.

Maybe you are looking for

  • Error in J1IEX

    Dear SAP Gurus, When I am posting a Vendor excise invoice ( T.code j1iex) after simulation Ecess ( Tax for education cess) is not being shown in the data. Can anybody clarify me what might be the problem, Thanks in advance.

  • Flash player version

    When trying to launch a Flex app I get an error saying I need player version 10. But I have version 9 debugger installed on all browsers. I know that the app that I'm trying to launch was developed with Flex Builder 3 (which comes with player version

  • HT4972 I have pictures on my iPhone and they aren't updating on iPad - why?

    Ihave tried synching. Wifi is on, icloud is on and still not updating to other devices. I have no idea what operating system I have - totally not tech savvy. Help please. Thx!

  • Document for conversion

    [email protected] How do I download a scanned form doc. for written collaboration and sharing?

  • Microsoft office crashes whenever I print

    Since I bought my new Macbook Air and transferred everything from my old Macbook Air via time machine, I have not been able to print from Microsoft office programs, and even when I print to PDF.  Anyone can help?