Unable to paint (using paint() in JPanel) inside mouse listeners

This is hard to explain but I'll do my best :)
I've created a little game and at some point I needed to make images "move" on the JPanel (through paint()), on a checkers-based game board.
The game works like so:
it has a mouse listener for clicks and movement, and the main game process is THINK(), REPAINT(), which is repeated until the user wins (the above is inside a while).
The mouse actions were added to the constructor so they are always active, THINK changes the enemy's locations, and REPAINT simply calls "paint()" again.
The picture is either an enemy or the player, and it can only "rest" on squares.
(e.g. point's x and y must be divided in 50).
While doing that, I wanted to make the movement more sleek and clean,
instead of them simply jumping from one square to the other with a blink of the eye.
So, I've created MOVEACTOR, that "moves" an enemy or a player from its current point (actor.getPoint()) to the requested future square (futurePoint).
//actor = enemy or player, has getPoint() that returnes the current point on the board where he rests on.
//futurePoint = the new point where the enemy or player should be after the animation.
//please ignore obvious stuff that has nothing to do with what I asked -- those will be deleted in the future, for they are only temporary checking extra lines and stuff.
//also feel free to ignore the "jumpX" things. Those are just to change images, to imitate physical "jumping" animation.
protected void moveActor(Actor actor, Point futurePoint)
          Point presentPoint = actor.getPoint();
          int x = (int)presentPoint.getX(), y = (int)presentPoint.getY();
          int addToX, addToY;
          if (futurePoint.getX() > x) addToX = 1;
          else addToX = -1;
          if (futurePoint.getY() > y) addToY = 1;
          else addToY = -1;
          Point middlePoint = new Point(x,y);
          int imageCounter = 0;
          while ( (middlePoint.getX()!=futurePoint.getX()) && (middlePoint.getY()!=futurePoint.getY()) ){
               imageCounter++;
               x+=addToX;
               y+=addToY;
               middlePoint.setLocation(x,y);
               actor.setPoint(middlePoint);
               /*if (imageCounter<=10) actor.setStatus("jump1");
               else if (imageCounter<=40) actor.setStatus("jump2");
               else if (imageCounter<=50) actor.setStatus("jump3");*/
               repaint();
               try {animator.sleep(1);} catch (InterruptedException e) {}
          //actor.setStatus("idle");
     }I use the above on several occasions:
[1] When an enemy moves. Summary:
                         if (playerIsToVillainsRight) xToAdd = 50;
                         else if (playerIsToVillainsLeft) xToAdd = -50;
                         else if (playerIsOnSameRowAsVillain) xToAdd = 0;
                         if (playerIsBelowVillain) yToAdd = 50;
                         else if (playerIsAboveVillain) yToAdd = -50;
                         else if (playerIsOnSameColumnAsVillain) yToAdd = 0;
                         Point futurePoint = new Point (villainX+xToAdd, villainY+yToAdd);
                         moveActor(actors[currentVillain], futurePoint);[2] When the player moves. Summary (this is inside the mouseClicked listener):
//mouseLocation = MouseWEvent.getPoint();
//stl, str, etc = rectangles that represents future location of the player on the board.
          if (waitingForPlayer) {
               if (stl.contains(mouseLocation) && !hoveringVillain(stl)) {
                    moveActor(actors[0], stl.getLocation());
                    waitingForPlayer = false;
               if (str.contains(mouseLocation) && !hoveringVillain(str)) {
                    moveActor(actors[0], str.getLocation());
                    waitingForPlayer = false;
               if (sbl.contains(mouseLocation) && !hoveringVillain(sbl)) {
                    moveActor(actors[0], sbl.getLocation());
                    waitingForPlayer = false;                                   
               if (sbr.contains(mouseLocation) && !hoveringVillain(sbr)) {
                    moveActor(actors[0], sbr.getLocation());
                    waitingForPlayer = false;
SO ... WHAT IS THE QUESTION?!?
What I see when I run the game:
the animation of the enemy (first code) works, but the animation of the player (second code, inside the mouse listeners) -- doesn't!
The purpose of the moveActor is to move the enemy or player pixel by pixel, until its in the future point,
instead of skipping the pixels between the squares and going straight for the future location.
So what comes out is, that the enemy is moving pixel by pixel, and the player simply jumps there!
I doublechecked and if I use moveActor with the player OUTSIDE the mouse listener, it works (i think).
Any ideas what is the source of this problem?
Hope I made myself clear enough :D
Thanks,
Eshed.

I don't know if thats what happens, nor how to fix the thread problems. The mosue actions are "threaded" by default, no? And the moving thing happens after the mouse was clicked, and if the enemy's moving the user can still move his mouse and get responses, like "enemy didn't move yet" and stuff.
Here's the complete GamePanel.java:
//drawings
import javax.swing.ImageIcon;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
//events
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
//tools
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.MediaTracker;
import java.awt.Dimension;
//panels, buttons, etc
import javax.swing.JPanel;
/** The Game Panel.
*The panel's size is 500x500, and each square is squaresized 50.
*This is where the game actually "exists". Here its being updated, drawn, etc.*/
public class GamePanel extends JPanel implements Runnable
     private static final int PWIDTH = 500;                              //Width of the panel.
     private static final int PHEIGHT = 500;                              //Height of the panel.
     private static final int SQUARESIZE = 50;                         //Size of each square in the panel.
     private boolean working = false;                                   //Game keeps going until this is FALSE.
     private volatile Thread animator;                                   //The animation thread.
     private ImageIcon stand,fall;                                        //Images for the background - ground and water.
     private static ImageHandler ih;                                        //An image handler for image loading.
     private int numOfImages = 0;                                        //Number of total images (max image qunatity).
     private Actor[] actors;                                                  //The actors: [0] is the player, rest are enemies.
     private Point mouseLocation;                                        //Saves the current mouse location for checking where the mouse is
     protected Rectangle stl, str, sbl, sbr;                              //squares around the player, for mouse stuff.
     protected Rectangle v1, v2, v3, v4, v5;                              //squares around each villain, for mouse stuff.
     protected Rectangle wholeBoard = new Rectangle(0,0,PWIDTH,PHEIGHT);
     protected boolean waitingForPlayer = true;
     private int currentVillain = 1;
     private boolean inSight = false;
     // in methods other than the listeners.
     /** Waits for the Window (or whatever this panel loads in) to settle in before doing anything.*/
     public void addNotify()
          super.addNotify();                                                                           //When the super finishes...
          go();                                                                                                         //..go, go, go!
     /** Starts the game.*/
     private void go()
          if (animator==null || !working)     {                                        //if the game isn't in process,
               animator = new Thread(this);                                        //make the animator as the main process,
               animator.start();                                                                      //and start it (because of the runnable it launches "run()".
     /**Constructor of the Game Panel.*/
     public GamePanel()
          numOfImages = 14;                                                                      //Total image num.
          ih = new ImageHandler(this,numOfImages);               //Setting a new image handler for the images.
          ih.addImage("player_idle", "images/p_idle.png");          //Adding images.
          ih.addImage("villain_idle", "images/v_idle.png");
          ih.addImage("stand", "images/stand.gif");
          ih.addImage("fallpng", "images/fall.png");
          ih.addImage("fall", "images/fall.gif");
          ih.addImage("ghost", "images/ghost.gif");
          ih.addImage("villain_angry", "images/v_angry.png");
          ih.addImage("player_angry", "images/p_angry.png");
          ih.addImage("player_jump1", "images/p_j1.gif");
          ih.addImage("player_jump2", "images/p_j2.gif");
          ih.addImage("player_jump3", "images/p_j3.gif");
          ih.addImage("villain_jump1", "images/v_j1.gif");
          ih.addImage("villain_jump2", "images/v_j2.gif");
          ih.addImage("villain_jump3", "images/v_j3.gif");
          setPreferredSize(new Dimension(PWIDTH,PHEIGHT));     //Setting size of the panel.
          setFocusable(true);                                                                                //This and the next makes the window "active" and focused.
          requestFocus();
          /** Mouse hovering settings.*/
          addMouseMotionListener( new MouseMotionAdapter()
               /** When the mouse is moving, do these stuff.*/
               public void mouseMoved(MouseEvent e1)
                     *  |  stl  |       | str   |          stl = squareTopLeft
                     *  |_______|_______|_______|       str = squareTopRight
                    *   |       |current|       |         current = player's location
                    *   |_______|_______|_______|       sbl = squareBottomLeft
                    *   |  sbl  |       |  sbr  |       sbr = squareBottomRight
                    *   |_______|_______|_______|
                    mouseLocation = e1.getPoint();
                    Dimension defaultSquareDimension = new Dimension(50,50);
                    //current-player-location points
                    Point topLeft = new Point((int)actors[0].getPoint().getX(), (int)actors[0].getPoint().getY());
                    Point topRight = new Point((int)actors[0].getPoint().getX()+50, (int)actors[0].getPoint().getY());
                    Point bottomLeft = new Point((int)actors[0].getPoint().getX(), (int)actors[0].getPoint().getY()+50);
                    Point bottomRight = new Point((int)actors[0].getPoint().getX()+50, (int)actors[0].getPoint().getY()+50);
                    //four-squares-around-the-player points
                    //T = top, B = bottom, R = right, L = left
                    Point ptl = new Point((int)topLeft.getX()-50,(int)topLeft.getY()-50);
                    Point ptr = new Point((int)topRight.getX(),(int)topRight.getY()-50);
                    Point pbl = new Point((int)bottomLeft.getX()-50,(int)bottomLeft.getY());
                    Point pbr = new Point((int)bottomRight.getX(),(int)bottomRight.getY());
                    //ghosts
                    stl = new Rectangle (ptl, defaultSquareDimension);
                    str = new Rectangle (ptr, defaultSquareDimension);
                    sbl = new Rectangle (pbl, defaultSquareDimension);
                    sbr = new Rectangle (pbr, defaultSquareDimension);
                    Rectangle player = new Rectangle(topLeft, defaultSquareDimension);     //rectangle of player
                    if (stl.contains(mouseLocation) && !hoveringVillain(stl))
                         actors[8] = new Actor("ghost", ptl);
                         else actors[8] = null;
                    if (str.contains(mouseLocation) && !hoveringVillain(str))
                         actors[9] = new Actor("ghost", ptr);
                         else actors[9] = null;
                    if (sbl.contains(mouseLocation) && !hoveringVillain(sbl))
                         actors[10] = new Actor("ghost", pbl);
                         else actors[10] = null;
                    if (sbr.contains(mouseLocation) && !hoveringVillain(sbr))
                         actors[11] = new Actor("ghost", pbr);
                         else actors[11] = null;
               private boolean hoveringVillain(Rectangle r)
                    boolean onVillain = false;
                    for (int i=1; i<=5 && !onVillain; i++) onVillain = actors.getRect().equals(r);
                    return onVillain;
          /** Mouse-click settings.
          Note: only usable after moving the mouse. /
          addMouseListener (new MouseAdapter()
               /** When the mouse button is clicked */
               public void mouseClicked (MouseEvent me)
                    mouseClickedAction(me);
     private boolean hoveringVillain(Rectangle r)
          boolean onVillain = false;
          for (int i=1; i<=5 && !onVillain; i++) onVillain = actors[i].getRect().equals(r);
          return onVillain;
     public void mouseClickedAction(MouseEvent me)
          System.out.println("Point: "+me.getX()+","+me.getY());
          if (waitingForPlayer) {
               //causes error if the mouse wasn't moved uptil now. try it.
               mouseLocation = me.getPoint();
               if (stl.contains(mouseLocation) && !hoveringVillain(stl)) {
                    moveActor(actors[0], stl.getLocation());
                    waitingForPlayer = false;
               if (str.contains(mouseLocation) && !hoveringVillain(str)) {
                    moveActor(actors[0], str.getLocation());
                    waitingForPlayer = false;
               if (sbl.contains(mouseLocation) && !hoveringVillain(sbl)) {
                    moveActor(actors[0], sbl.getLocation());
                    waitingForPlayer = false;                                   
               if (sbr.contains(mouseLocation) && !hoveringVillain(sbr)) {
                    moveActor(actors[0], sbr.getLocation());
                    waitingForPlayer = false;
          } else MiscTools.shout("Wait for the computer to take action!");
          if (actors[0].getPoint().getY() == 0){
               for (int i=1; i<=5; i++){
                         actors[i].setStatus("angry");
               //repaint();
               MiscTools.shout("Game Over! You Won!");
     /** First thing the Game Panel does.
     Initiating the variables, and then looping: updating, painting and sleeping./
     public void run() {
Thread thisThread = Thread.currentThread();                                                  //Enables the restart action (two threads needed).
init();                                                                                                                                            //Initialize the variables.
while (animator == thisThread && working){                                                  //While the current thead is the game's and it's "on",
               think();                                                                                                                             //Update the variables,
               repaint();                                                                                                                             //Paint the stuff on the panel,
               try {Thread.sleep(5);} catch (InterruptedException ex) {}                    //And take a wee nap.
     /** Initializing the variables.*/
     private void init()
          currentVillain = 1;
          working = true;                                                                                //Make the game ready for running.
          inSight = false;
          actors = new Actor[12];                                                                      //Six actors: player and 5*villains.
          actors[0] = new Actor("player", 200, 450);                                             //The first actor is the player.
          int yPoint = 50;                                                                           //The Y location of the villains (first row).
          /* ACTORS ON TOP, RIGHT, LEFT
          actors[1] = new Actor ("villain", 0, 350);
          actors[2] = new Actor ("villain", 0, 150);
          actors[3] = new Actor ("villain", 50, 0);
          actors[4] = new Actor ("villain", 250, 0);
          actors[5] = new Actor ("villain", 450, 0);
          actors[6] = new Actor ("villain", 450, 200);
          actors[7] = new Actor ("villain", 450, 400);
          /* ACTORS ON TOP*/
          for (int i=1; i<actors.length-4; i++){                                                  //As long as it doesnt go above the array...
               actors[i] = new Actor ("villain", yPoint, 0);                                   //init the villains
               actors[i].setStatus("idle");
               yPoint+=100;                                                                           //and advance in the Y axis.
     /** Updating variables.*/
     private void think()
          if (!waitingForPlayer){
               //initialize
               int playerX = (int)actors[0].getPoint().getX();
               int playerY = (int)actors[0].getPoint().getY();
               boolean moved = false;
               wholeBoard = new Rectangle(0,0,500,500);     //needed to check whether an actor is inside the board
               //for (int in = 0; in<=5; in++) actors[in].setStatus("idle"); //"formatting" the actor's mood
               if (playerY <= 1000) inSight = true;     //first eye contact between the player and villains.
               int closestVillainLevel = 0;
               int[] vills = closestVillain();
               int moveCounter = 0;
               if (inSight) {
                    while (!moved){               //while none of the villains made a move
                    moveCounter++;
                    if (moveCounter == 5) moved = true;
                    else{
                         currentVillain = vills[closestVillainLevel];
                         int villainX = (int)actors[currentVillain].getPoint().getX();
                         int villainY = (int)actors[currentVillain].getPoint().getY();
                         //clearing stuff up before calculating things
                         boolean playerIsBelowVillain = playerY > villainY;
                         boolean playerIsAboveVillain = playerY < villainY;
                         boolean playerIsOnSameRowAsVillain = playerY == villainY;
                         boolean playerIsToVillainsRight = playerX > villainX;
                         boolean playerIsToVillainsLeft = playerX < villainX;
                         boolean playerIsOnSameColumnAsVillain = playerX == villainX;
                         //System.out.println("\n-- villain number "+currentVillain+" --\n");
                         int xToAdd = 0, yToAdd = 0;
                         if (playerIsToVillainsRight) xToAdd = 50;
                         else if (playerIsToVillainsLeft) xToAdd = -50;
                         else if (playerIsOnSameRowAsVillain) xToAdd = 0;
                         if (playerIsBelowVillain) yToAdd = 50;
                         else if (playerIsAboveVillain) yToAdd = -50;
                         else if (playerIsOnSameColumnAsVillain) yToAdd = 0;
                         Point futurePoint = new Point (villainX+xToAdd, villainY+yToAdd);
                         if (legalPoint(futurePoint)){
                              moveActor(actors[currentVillain], futurePoint);
                              moved = true;
                              //System.out.println("\nVillain "+currentVillain+" is now at "+actors[currentVillain].getPoint());
                         else closestVillainLevel=circleFive(closestVillainLevel);
                    } //end of else
                    } //end of while
                    //currentVillain = circleFive(currentVillain); //obsolete
               } //end of ifInSight
               waitingForPlayer = true;
     private boolean legalPoint(Point fp)
          return (wholeBoard.contains(fp) && !onPeople(fp) && legalSquare(fp));
     private boolean legalSquare(Point p)
          if ( (p.getX()==0 || p.getX()%100==0) && (p.getY()/50)%2!=0 ) return true;
          if ( (p.getX()/50)%2!=0 && (p.getY()==0 || p.getY()%100==0) ) return true;
          return false;
     //return the closest villain to the player, by its level of distance.
     public int[] closestVillain()
          //System.out.println("Trying to find the closest villain...");
          double[] gaps = new double[5];     //the distances array
          //System.out.println("The villains' distances are: ");
          for (int i=0; i<5; i++){
               gaps[i] = distanceFromPlayer(actors[i+1].getPoint());     //filling the distances array
               //System.out.print(gaps[i]+", ");
          int[] toReturn = new int[5];
          double smallestGapFound;
          double[] arrangedGaps = smallToLarge(gaps);
          for (int level=0; level<5; level++){
               smallestGapFound = arrangedGaps[level];
               for (int i=1; i<=5; i++){
                    if (smallestGapFound == distanceFromPlayer(actors[i].getPoint())){
                         toReturn[level] = i;
          return toReturn;
     private double[] smallToLarge(double[] nums)
          //System.out.println("\nArranging array... \n");
          double[] newArray = new double[5];
          int neweye = 0;
          double theSmallestOfTheArray;
          for (int i=0; i<nums.length; i++){
               theSmallestOfTheArray = smallest(nums);
               //System.out.println("\t\t>> Checking whether location "+i+" ("+nums[i]+") is equal to "+theSmallestOfTheArray);
               if (nums[i] == theSmallestOfTheArray && nums[i]!=0.0){
                    //System.out.println("\t\t>> Adding "+nums[i]+" to the array...");
                    newArray[neweye] = nums[i];
                    //System.out.println("\t\t>> Erasing "+nums[i]+" from old array...\n");
                    nums[i] = 0.0;
                    neweye++;
                    i=-1;
          /*System.out.print("\nDONE: ");
          for (int i=0; i<newArray.length; i++)
               System.out.print("["+newArray[i]+"] ");
          System.out.println();*/
          return newArray;
     private double smallest (double[] nums)
               //System.out.print("\tThe smallest double: ");
               double small = 0.0;
               int j=0;
               while (j<nums.length){               //checking for a starting "small" that is not a "0.0"
                    if (nums[j]!=0.0){
                         small = nums[j];
                         j = nums.length;
                    } else j++;
               for (int i=1; i<nums.length; i++){
                    if (small>nums[i] && nums[i]!=0.0){
                         small = nums[i];
               //System.out.println(small+".");
               return small;
     private double distanceFromPlayer(Point vp)
          Point pp = actors[0].getPoint(); //pp=plaer's point, vp=villain's point
          double x = Math.abs(vp.getX() - pp.getX());
          double y = Math.abs(vp.getY() - pp.getY());
          return Math.sqrt(Math.pow(x,2) + Math.pow(y,2));
     private int circleFive(int num)
               if (num>=5) return 0;
               else return num+1;
     private boolean onPeople(Point p)
          for (int jj=0; jj<=5; jj++)
               if (jj!=currentVillain && p.equals(actors[jj].getPoint()))
                    return true;
          return false;
     /** Painting the game onto the Game Panel.*/
     public void paintComponent(Graphics g)
          Graphics2D graphics = (Graphics2D)g;                                                            //Reset the graphics to have more features.
          //draw bg
          graphics.setColor(Color.white);                                                                                //"format" the panel.
          graphics.fillRect(0,0,500,500);
     char squareType = 'f';                                                                                                    //First square's type (stand or fall).
     for (int height=0; height<PHEIGHT; height=height+SQUARESIZE){     //Painting the matrix bg.
               for (int width=0; width<PWIDTH; width=width+SQUARESIZE){
                    if (squareType=='f') {                                                                                               //If a "fall" is to be drawn,
                         ih.paint(graphics, "fallpng", new Dimension(width,height));          //Draw a non-animated image to bypass white stuff.
                         ih.paint(graphics, "fall", new Dimension(width,height));               //Draw the water animation.
                         squareType = 's';                                                                                                    //Make the next square a "stand".
                    } else if (squareType=='s'){                                                                                //If a "stand" is to be drawn,
                         ih.paint(graphics, "stand", new Dimension(width,height));          //Draw the ground image,
                         squareType = 'f';                                                                                                    //and make the next square a "fall".
               if (squareType=='f') squareType = 's';                                                                 //After finishing a row, switch again so
               else squareType = 'f';                                                                                                    // the next line will start with the same type (checkers).
          for (int i=actors.length-1; i>=0; i--){                                                                           //Draw the actors on the board.
               if (actors[i]!=null)
                    ih.paint(graphics, actors[i].currentImage(), actors[i].getPoint());
     /** Restart the game.
     Or, in other words, stop, initialize and start (again) the animator thread and variables./
     public void restart()
          System.out.println("\n\n\nRESTARTING GAME\n\n\n");
          animator = null;                                                                                                                   //Emptying the thread.
          init();                                                                                                                                                 //Initializing.
          animator = new Thread(this);                                                                                     //Re-filling the thread with this panel's process.
          animator.start();                                                                                                                   //launch "run()".
     protected void moveActor(Actor actor, Point futurePoint)
          Point presentPoint = actor.getPoint();
          int x = (int)presentPoint.getX(), y = (int)presentPoint.getY();
          int addToX, addToY;
          if (futurePoint.getX() > x) addToX = 1;
          else addToX = -1;
          if (futurePoint.getY() > y) addToY = 1;
          else addToY = -1;
          Point middlePoint = new Point(x,y);
          int imageCounter = 0;
          while ( (middlePoint.getX()!=futurePoint.getX()) && (middlePoint.getY()!=futurePoint.getY()) ){
               imageCounter++;
               x+=addToX;
               y+=addToY;
               middlePoint.setLocation(x,y);
               actor.setPoint(middlePoint);
               /*if (imageCounter<=10) actor.setStatus("jump1");
               else if (imageCounter<=40) actor.setStatus("jump2");
               else if (imageCounter<=50) actor.setStatus("jump3");*/
               repaint();
               try {animator.sleep(1);} catch (InterruptedException e) {}
          //actor.setStatus("idle");

Similar Messages

  • (Another) problem with custom painting using JApplet and JPanel

    Hi all,
    I posted regarding this sort of issue yesterday (http://forums.sun.com/message.jspa?messageID=10883107). I fixed the issue I was having, but have run into another issue. I've tried solving this myself to no avail.
    Basically I'm working on creating the GUI for my JApplet and it has a few different JPanels which I will be painting to, hence I'm using custom painting. My problem is that the custom painting works fine on the mainGUI() class, but not on the rightGUI() class. My code is below:
    import javax.swing.*;
    import javax.swing.border.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.imageio.*;
    public class TetrisClone extends JApplet {
         public void init() {
              setSize( 450, 500 );
              Container content = getContentPane();
              content.add( new mainGUI(), BorderLayout.CENTER );
              content.add( new rightGUI() , BorderLayout.LINE_END );
    class mainGUI extends JPanel {
         // Main bit where blocks fall
         public mainGUI() {
              setBackground( new Color(68,75,142) );
              setPreferredSize( new Dimension( 325, 500 ) );
              validate();
         public Dimension getPreferredSize() {
              return new Dimension( 450, 500 );
         public void paintComponent( Graphics g ) {
              super.paintComponent(g);
              // As a test. This shows up fine.
              g.setColor( Color.black );
              g.fillRect(10,10,100,100);
              g.setColor( Color.white );
              g.drawString("Main",45,55);
    class rightGUI extends JPanel {
         BufferedImage img = null;
         int currentLevel = 0;
         int currentScore = 0;
         int currentLines = 0;
         public rightGUI() {
              // The right panel. Has quite a few bits. Starts here..
              FlowLayout flow = new FlowLayout();
              flow.setVgap( 20 );
              setLayout( flow );
              setPreferredSize( new Dimension( 125, 500 ) );
              setBackground( new Color(27,34,97) );
              setBorder( BorderFactory.createMatteBorder(0,2,0,0,Color.black) );
              // Next block bit
              JPanel rightNext = new JPanel();
              rightNext.setPreferredSize( new Dimension( 100, 100 ) );
              //rightNext.setBackground( new Color(130,136,189) );
              rightNext.setOpaque( false );
              rightNext.setBorder( BorderFactory.createEtchedBorder(EtchedBorder.LOWERED) );
              Font rightFont = new Font( "Courier", Font.BOLD, 18 );
              // The player's playing details
              JLabel rightLevel = new JLabel("Level: " + currentLevel, JLabel.LEFT );
              rightLevel.setFont( rightFont );
              rightLevel.setForeground( Color.white );
              JLabel rightScore = new JLabel("Score: " + currentScore, JLabel.LEFT );
              rightScore.setFont( rightFont );
              rightScore.setForeground( Color.white );
              JLabel rightLines = new JLabel("Lines: " + currentLines, JLabel.LEFT );
              rightLines.setFont( rightFont );
              rightLines.setForeground( Color.white );
              JPanel margin = new JPanel();
              margin.setPreferredSize( new Dimension( 100, 50 ) );
              margin.setBackground( new Color(27,34,97) );
              JButton rightPause = new JButton("Pause");
              try {
                  img = ImageIO.read(new File("MadeBy.gif"));
              catch (IOException e) { }
              add( rightNext );
              add( rightLevel );
              add( rightScore );
              add( rightLines );
              add( margin );
              add( rightPause );
              validate();
         public Dimension getPreferredSize() {
                   return new Dimension( 125, 500 );
         public void paintComponent( Graphics g ) {
              super.paintComponent(g);
              g.setColor( Color.black );
              g.drawString( "blah", 425, 475 ); // Doesn't show up
              g.drawImage( img, 400, 400, null ); // Nor this!
              System.out.println( "This bit gets called fine" );
    }Any help would be greatly appreciated. I've read loads of swing and custom painting tutorials and code samples but am still running into problems.
    Thanks,
    Tristan Perry

    Many thanks for reminding me about the error catching - I've added a System.out.println() call now. Anywhoo, the catch block never gets run; the image get call works fine.
    My problem was/is:
    "My problem is that the custom painting works fine on the mainGUI() class, but not on the rightGUI() class. My code is below:"
    I guess I should have expanded on that. Basically whatever I try to output in the public void paintComponent( Graphics g ) method of the rightGUI class doesn't get output.
    So this doesn't output anything:
    g.drawString( "blah", 425, 475 ); // Doesn't show up
    g.drawImage( img, 400, 400, null ); // Nor this!
    I've checked and experimented with setOpaque(false), however this doesn't seem to be caused by any over-lapping JPanels or anything.
    Let me know if I can expand on this :)
    Many thanks,
    Tristan Perry
    Edited by: TristanPerry on Dec 10, 2009 8:40 AM

  • Unable to find SCREEN PAINT

    i am unable to find SCREEN PAINT option while i created an new company and new DATA Base. Can any one resolve my issue.

    Hi,
    What version of B 1 you are using?
    go to admin>>addons>>add on administration.....check here that screen painter addon is installed or not ?
    if you do not find here screen painter then go to your SAP B 1 dump >>packeges>>screen painter>>run the .exe file
    Regards
    Deepak Tyagi

  • How to use paint method to draw in many componets.

    Hi!
    I have code like this:
    public class MainPanel extends JPanel{
       JPanel p1;
       JPanel p2;
       public MainPanel(){
           super(new BorderLayout());
           p1 = new JPanel();
           p2 = new JPanel();
           add(p1 , BorderLayout.Center);
           add(p2 , BorderLayout. West);
           setVisible(true);
    @Override
        protected void paintComponent(Graphics g) {
           g.setColor(Color.red);
           g.fillrect(10,10,10,10);
    }This code is onle an example. Supose, this code will paint black rectangle on "main panel" to which p1 and p2 are added. What should i do to be able to paint this rectangle on p1 or p2 without creating separate classes in which i will override paintComponents() method for p1 and p2. I would like to avoid creating separete classes for each panels. Is there any way to do that using one paint Components method. Thanks in advance for all respone.

    (where's Darryl when you need him?)Erm, Pete, since when did I become an expert lol?
    Lost my hard disk, its been hiccuping for a couple of weeks now. I'm running on an old 20 GB PATA with a 5GB c drive. No IDE, no offline Javadoc. I'll get a HDD in the morning, but I hope I can spin up the old disk at least once and recover the last week's "work" ... just fun stuff actually.
    Why does this code draw rectangles just for split second?repaint() (and consequently paint(), paintComponent() and other painting methods) may be called by the system any time it is detected that the component needs to be repainted. Since you do not have a override for paintComponent, it will perform its default painting and paint the entire component, wiping out your rectangle.
    For persistent drawing on a JPanel or JComponent I know only one way: override paintComponent. If you need to avoid this, you could go with morgalr's suggestion to use JLabel.
    For this you would draw the triangle/rectangle/whatever to a BufferedImage, then call label.setIcon with a new ImageIcon constructed from the BufferedImage.
    Also, avoid obtaining a Graphics reference via getGraphics. During the lifetime of a visible component, various different Graphics references may be passed into the paintComponent method, so the reference you obtain may not be current. getGraphics can also return null.
    luck, db

  • Using Paint in JFrame

    I am trying to divide a frame into a number of different rectangles, and for some reason I can't get the paintComponent to work. Help!!

    I was wrong in reply one. The paint method in JFrame shows up in the Container methods section, so JFrame uses paint as a Container.
    import java.awt.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class PaintingDemo extends JPanel {
      int
        width,
        height;
      int[][] circles = {
        {2,20}, {100,50}, {180,200}, {90,150}
      int[][] squares = {
        {40,90}, {100,200}, {150,300}
      int[][] rectangles = {
        {100,100}, {200,100}, {300,300}
      public PaintingDemo(int width, int height) {
        this.width = width;
        this.height = height;
        setBackground(Color.pink);
        setPreferredSize(new Dimension(width, height));
      public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                            RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setPaint(Color.blue);
        int x,y;
        for(int i = 0; i < circles.length; i++) {
          x = circles[0];
    y = circles[i][1];
    g2.fill(new Ellipse2D.Double(x, y, 20, 20));
    g2.setPaint(Color.red);
    for(int i = 0; i < squares.length; i++)
    g2.fill(new Rectangle2D.Double(squares[i][0], squares[i][1], 10, 10));
    g2.setPaint(Color.orange);
    for(int i = 0; i < rectangles.length; i++)
    g2.fill(new Rectangle2D.Double(rectangles[i][0], rectangles[i][1], 50, 25));
    public static void main(String[] args) {
    JFrame f = new JFrame();
    f.getContentPane().add(new PaintingDemo(400,400));
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.pack();
    f.setLocationRelativeTo(null);
    f.setVisible(true);

  • How to show screen design in .srf (from Screen Painter) using SDK?

    How to show screen design in .srf (from Screen Painter) using SDK?

    You need to use the LoadBatchActions method of the Application object to load .SRF files.
    John.

  • Elements 10, windows 8, 64 bit, epson artisan 835 printer: prints are really dark even after using enhancements like adjusting lighting. Prints are darker than photoshop edit screen. Prints are acceptable using paint, windows photo viewer, or gallery.

    Elements 10, Windows 8, 64 bit, Epson Artisan 835 printer: Prints are really dark even after applying enhancements, like adjusting lighting. Prints are darker than Photoshop Edit Screen. Prints are acceptable using Paint, Windows Photoviewer, or Photo Gallery.

    In general theory, one now has the Edit button for their posts, until someone/anyone Replies to it. I've had Edit available for weeks, as opposed to the old forum's ~ 30 mins.
    That, however, is in theory. I've posted, and immediately seen something that needed editing, only to find NO Replies, yet the Edit button is no longer available, only seconds later. Still, in that same thread, I'd have the Edit button from older posts, to which there had also been no Replies even after several days/weeks. Found one that had to be over a month old, and Edit was still there.
    Do not know the why/how of this behavior. At first, I thought that maybe there WAS a Reply, that "ate" my Edit button, but had not Refreshed on my screen. Refresh still showed no Replies, just no Edit either. In those cases, I just Reply and mention the [Edit].
    Also, it seems that the buttons get very scrambled at times, and Refresh does not always clear that up. I end up clicking where I "think" the right button should be and hope for the best. Seems that when the buttons do bunch up they can appear at random around the page, often three atop one another, and maybe one way the heck out in left-field.
    While I'm on a role, it would be nice to be able to switch between Flattened and Threaded Views on the fly. Each has a use, and having to go to Options and then come back down to the thread is a very slow process. Jive is probably incapable of this, but I can dream.
    Hunt

  • Confused about how to use paint()

    Hi, I have been working really hard to try to get the following program to work but I am really confused on how to use paint(). I do not have anyone to ask so I thought this forum could help. Anyways, here is my problem...
    I am trying to recursively figure out the Sierpinski fractal. I cannot figure out if my math works or not because I do not know how to call the paint() recursively to draw my triangles.
    Please have a look at the following code. Thank you!
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    public class DrawTriangle extends Frame {
      Point a = new Point(20,480),
            b = new Point(350,40),
            c = new Point(680,480),
            halfB,
            halfC,
            halfB2,
            halfC2,
            halfC3;
      int width;
      public DrawTriangle() {
        super("Sierpinski Fractal");
        addWindowListener( new WindowAdapter() {
          public void windowClosing( WindowEvent we ) {
            dispose();
            System.exit( 0 );
        setBackground( Color.white );
        setSize(700, 500);
        setVisible(true);
      public void paint(Graphics g, Point a, Point b, Point c) {
        width = c.x - a.x;
        if (width < 6){return;}
        g.setColor( Color.GREEN );
        g.drawPolygon( new int[] { a.x, b.x, c.x }, new int[] { a.y, b.y, c.y }, 3 );
        halfC.x = c.x/2;
        halfC.y = c.y;
        halfB.y = b.y/2;
        halfB.x = b.x;
        halfB2.y = halfB.y + a.y;
        halfB2.x = a.x;
        halfC2.x = halfC.x + a.x;
        halfC2.y = a.y;
        halfC3.x = halfC.x/2 + a.x;
        halfC3.y = halfB2.y;
        paint(g, a, halfC, halfB);
        paint(g, halfC3, halfC, halfB);
        paint(g, halfC2, halfC, halfB);
      public static void main(String[] args) {
         new DrawTriangle();

    thanks jsalonen, your tip let me start working on the math to correct it.
    I have a new problem now. My math is correct but I am having problems with the recursion. I can draw only the top , left , or right triangles. I cannot get them all to work together. See code and comments below.
    Any ideas why I cant call all three of the paint()s toegther and have them work?
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    public class DrawTriangle extends Frame {
      Point a = new Point(20,480),
            b = new Point(350,40),
            c = new Point(680,480),
            halfA,
            halfB,
            halfC;
      int width;
      public DrawTriangle() {
        super("Sierpinski Fractal");
        addWindowListener( new WindowAdapter() {
          public void windowClosing( WindowEvent we ) {
            dispose();
            System.exit( 0 );
        setBackground( Color.white );
        setSize(700, 500);
        setVisible(true);
      public void paint(Graphics g)
      paint(g, a, b, c);
      public void paint(Graphics g, Point a, Point b, Point c) {
        width = c.x - a.x;
        if (width < 6){return;}
        halfA = new Point((a.x+b.x)/2, (a.y+b.y)/2);
        halfB = new Point((a.x+c.x)/2, (a.y+c.y)/2);
        halfC = new Point((b.x+c.x)/2, (b.y+c.y)/2);
        g.setColor( Color.GREEN ); //draw left triangle in green
        g.drawPolygon( new int[] { a.x, halfA.x, halfB.x }, new int[] { a.y, halfA.y, halfB.y }, 3 );
        g.setColor( Color.RED ); //draw top triangle in red
        g.drawPolygon( new int[] { b.x, halfA.x, halfC.x }, new int[] { b.y, halfA.y, halfC.y }, 3 );
        g.setColor( Color.BLUE ); //draw right triangle in blue
        g.drawPolygon( new int[] { c.x, halfB.x, halfC.x }, new int[] { c.y, halfB.y, halfC.y }, 3 );
        /*If you were to comment our two of these paint() calls the one will work correctly alone.
         *But my problem is that they do not work together! */
        //g, left point, top point, right point
        paint(g, halfA, b, halfC); //top triangle
        paint(g, halfC, halfB, c); //right triangle
        paint(g, a, halfA, halfB); //left triangle
      public static void main(String[] args) {
         new DrawTriangle();
    }

  • RuntimeException: Maximum number of gradient stops exceeded (paint uses 17

    I run into this exception occasionally
    java.lang.RuntimeException: Maximum number of gradient stops exceeded (paint uses 17 stops, but max is 12)
    at com.sun.prism.impl.ps.PaintHelper.stopsToImage(PaintHelper.java:94)
    at com.sun.prism.impl.ps.PaintHelper.initGradient(PaintHelper.java:137)
    at com.sun.prism.impl.ps.PaintHelper.setMultiGradient(PaintHelper.java:164)
    at com.sun.prism.impl.ps.PaintHelper.setLinearGradient(PaintHelper.java:271)
    at com.sun.prism.impl.ps.BaseShaderContext.updatePaintShader(BaseShaderContext.java:208)
    at com.sun.prism.impl.ps.BaseShaderContext.validatePaintOp(BaseShaderContext.java:378)
    at com.sun.prism.impl.ps.BaseShaderContext.validatePaintOp(BaseShaderContext.java:325)
    at com.sun.prism.impl.ps.BaseShaderContext.validatePaintOp(BaseShaderContext.java:284)
    at com.sun.prism.impl.BaseContext.validateClearOp(BaseContext.java:78)
    at com.sun.prism.d3d.D3DGraphics.clear(D3DGraphics.java:64)
    at com.sun.javafx.tk.quantum.PaintRunnable.doPaint(PaintRunnable.java:206)
    at com.sun.javafx.tk.quantum.PaintRunnable.paintImpl(PaintRunnable.java:145)
    at com.sun.javafx.tk.quantum.PaintRunnable.run(PaintRunnable.java:349)
    at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
    at java.util.concurrent.FutureTask$Sync.innerRunAndReset(Unknown Source)
    at java.util.concurrent.FutureTask.runAndReset(Unknown Source)
    at com.sun.prism.render.RenderJob.run(RenderJob.java:29)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
    at com.sun.javafx.tk.quantum.QuantumRenderer$PipelineRunnable.run(QuantumRenderer.java:101)
    at java.lang.Thread.run(Unknown Source)
    Running javafx 2.0.2 with java 1.7.02 on windows 7
    Anyone else encountered this and is there a workaround?
    In the system there is are rectangles with fill to something similar to
    -fx-fill: linear-gradient(from 0% 0% to 100% 0%, rgb(177,177,177) 0%, rgb(255,128,255) 7%, rgb(210,59,54) 12%, rgb(248,100,100) 22%, rgb(252,180,180) 43%, rgb(250,200,200) 44%, rgb(170,170,170) 45%, rgb(248,248,248) 46%, rgb(248,248,248) 59%, rgb(200,200,200) 62%, rgb(180,180,180) 64%, rgb(167,167,167) 65%, rgb(200,200,200) 67%, rgb(248,248,248) 70%, rgb(248,248,248) 90%, rgb(200,200,200) 95%, rgb(166,185,238) 100%);In this case, there are 17 stops to this linear-gradient. If the number of stops is lowered, the exception occurs less often. Based on the exception, it looks like if there is a gradient with more than 12 stops, it is possible to run into this exception.
    Thanks
    Edited by: 907429 on Jan 12, 2012 10:18 AM

    Please post a short reproducible test case surrounded with markers and/or log a bug with a reproducible test case at http://javafx-jira.kenai.com                                                                                                                                                                                                                                                                                                               

  • Create Report Painter using LIS table

    Hi Expert,
    I'n new in ECC version but I found we can create report painter using LIS table,
    but I'm not success to create report without error or debug
    Anybody have the documentation about it ?  or tell me how it works ...
    Please ..urgent...need to tell client about it..
    Thanks

    Hi,
    I have not worked on it but you can try this out:
    TCODE for report writer table is GRCT.
    There You need to add your z fields in some pre-defined structure like CCSS and then activate the structure and then activate characteristics.
    NOTE: 24 charcter is max. length for the characteristics.
    Regards,
    Harsh.

  • When to use Paint over Photoshop?

    Im newer to Photoshop so its easier for me to throw my images into Paint to resize and crop them.
    I was curious if other community members ever use Microsoft Paint for tasks and if so what?
    Also, should I be doing this or would it benefit me to use Photoshop for resizing and croping images?  I plan on using Photoshop but I rarely have it open since I mostly use the development programs within CS5 and it takes magnitudes longer to open Photoshop than Paint.  But even with Fireworks running and the image attended for Fireworks I still through my image into paint because it seems faster.  Am I dumb? Should I give up the paint? Some hot keys for this task probably would be better ahhhh... any insight?
    Thanks,

    I do not think that I have used MS Paint, since about Windows 2.0. I did not even realize that it was still around.
    I just use PS for everything, with the exception of JPEG's, with bum header info, that PS will not open. Then, I just use either ThumbsPlus, or IrfanView, to Open, then Save with proper header info.
    I do not have any data on the Scaling (Resizing) algorithms in Paint, but would think that those in PS would be better. They do offer you a good range of choices, but maybe Paint has similar? Same when Cropping. What part of those operations do you find easier in Paint?
    Though I use PS a lot, and have for a very long time, image editing software is but a tool in a process. Using the right tool, or the one that the artist is most comfortable with, is the trick. I use Painter (now Corel) for a lot of treatments, but almost always finish up in PS. Over the decades, PS has become closer to Painter, than in days past. Still, there are treatments that I want to apply in Painter, and part of those choices will be my personnal comfort level. I might have something very similar in my newer PS, but if I know every step by heart in Painter, my comfort level rises.
    Use what you like for different operations, but I would do a visual check with an operation, like Scale/Resize. Do the same exact operation in each program, using the same base Image, and the same exact settings. Compare the results of the two programs critically.
    Good luck,
    Hunt

  • Cannot use paint bucket on 32bit

    i am trying to isolate the chrome ball part in my picture. and I have made a selection around my chromeball and ctrl+shift+i to reverse my selection.
    and then I tried to fill it in with black color using paint bucket and it poped error message that saying it doesn't support 32bit?
    I am following the tutorial on digital tutor and it works according to the tutorial and how come it is not working on my photoshop?

    Yes, the paint bucket doesn't work in 32 bit/channel. Underneath it has some assumptions about the range of the image data that will take a while to resolve.
    But the Fill command works just fine.

  • PC users are always talking about using "paint".  Is there anything comparable on a Mac?

    PC users are always talking about using "paint" to circle things in a picture.  Is there anything comparable on a Mac?

    Open the picture in Preview and you can circle things using the Annotate tools.
    Or use Preview/Tools menu to access.

  • Graphics without using paint

    Hi!
    I want to draw somthing without using paint. Does anyone know how to do that?
    f.eks
    I want to call a function with some parameters, and then the function draws something for me with these parameters.
    Thanks for helping:)
    Best regards
    Stian

    Sure... You could use the function to generate an image file and load that using ImageIcon and pass that to a JLabel.
    But that's not going to work nearly as fast as just using paint.

  • Difference between paint() and paint() after resize

    Hello,
    I have an application where I am painting a plot on a JPanel inside a JInternalFrame.
    If I just call JPanel.repaint everything gets painted in the correct position.
    The problem comes when I am resizing the JPanel via the JInternalFrame. In that
    case the paint code retrieves the bounds of the JPanel and plots only some of
    the items in the wrong place. The errant positions indicate that the paint is retrieving
    a JPanel bounds for some items that reflects one of the JPanel sizes before
    resizing stops.
    How can I ensure that my paint() code is only getting the size of the JPanel after
    resizing has stopped?
    Thanks for any info,
    P

    DrClap wrote:
    You can't. Because no part of your application can tell when that happens.
    Try it with some application that you're familiar with. Like the browser you're using right now. Grab one of the window edges and drag it to make the window
    smaller. Now stop dragging, but don't lift your finger off the mouse button. See how the browser redisplays itself, even though resizing might not have stopped yet?
    Good point.
    I was under the impression that resize stopped when the mouse button was released.
    But, now that you mention it, things are being redrawn while resize is happening.
    Thanks
    P

Maybe you are looking for