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);

Similar Messages

  • 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();
    }

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

  • Using paint() for a JPanel in a ScrollBar

    i have a class that extends JPanel and paints some graphics in it using the function paint(). like g.drawString.. i had to add an instantition of that class in the container of my main class within a scrollbar. It initially painted well but when i scroll, it gets distorted. its something like this
    public class PaintedPane extends JPanel
    public PaintedPane()
    paint()
    other codes here..
    public class MainClass extends JFrame
    public PaintedPane pane;
    public JScrollbar scroll;
    public MainClass()
    pane = new PaintedPane();
    scroll = new JScrollBar(pane);
    it seems that the pane wont update the part of the pane not initially exposed because of the scrollBar. how can i fix it? thanks!

    sorry for the wrong section.
    here is the code:
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class MainClass extends JFrame
         public TextDraw td;
         public JScrollPane pane;
         public Container c;
         public MainClass()
              c = getContentPane();
              c.setLayout(new FlowLayout());
              td = new TextDraw();
              td.setPreferredSize(new Dimension(300, 300));
              pane = new JScrollPane(td);
              pane.setPreferredSize(new Dimension(300, 200));
              c.add(pane);
              setSize(400, 400);
              show();
         public static void main(String args[])
              MainClass m = new MainClass();
              m.addWindowListener(
                   new WindowAdapter()
                        public void windClosing(WindowEvent e)
                             System.exit(0);
    }and another java file for the TextDraw
    import javax.swing.*;
    import java.awt.*;
    public class TextDraw extends JPanel
       public TextDraw()
             setBackground(Color.WHITE);           
                setSize(500,  500);
                show();
       public void paint(Graphics g)
              for(int x = 0; x < 20; x++)
                   g.drawString("Hello world!", 20, (x)*20);
                   g.fillRect(5, (x)*20, 10, 10);
    }i dont realy know what to do to fix this. And if i chang the values of the "setSize(400, 400)" of the MainClass to "setSize(300, 300)" it works fine. why is it like that? sorry im not very familiar with all the paint, paintComponent and graphics things. thanks!

  • Why isn't my JComponent being painted onto JFrame

    I am using the Card class from Sun's enum examples. The Card class extends JComponent and each card has an Image field storing its graphic. My problem is that when getContentPane().add(card) is called, it doesn't show up on the JFrame. I have overridden paint() in both the Card class and JFrame to see if either will work, but they haven't. I'd appreciate any help.
    import java.util.List;
    import java.util.LinkedList;
    import java.awt.*;
    import javax.swing.JComponent;
    public class Card extends Component {
        public enum Rank {
            DEUCE (2),
            THREE (3),
            FOUR (4),
            FIVE (5),
            SIX (6),
            SEVEN (7),
            EIGHT (8),
            NINE (9),
            TEN (10),
            JACK (10),
            QUEEN (10),
            KING (10),
            ACE (11, 1);
    private final int value1, value2;
        Rank (int val) {
        this.value1 = val;
        this.value2 = 0;
        Rank (int val, int val2) {
        this.value1 = val;
        this.value2 = val2;
    public int val1() { return this.value1; }
    public int val2() { return this.value2; }
        public enum Suit { CLUBS, DIAMONDS, HEARTS, SPADES }
        private final Rank rank;
        private final Suit suit;
        private Image image;
        private static final List<Card> protoDeck = new LinkedList<Card>();
        public Card(Rank rank, Suit suit, String img) {
            super();
            this.rank = rank;
            this.suit = suit;
            this.image = Toolkit.getDefaultToolkit().createImage(img);
    // is the below method implementation right?
    public void paint(Graphics g) {
    boolean x = g.drawImage(image, 0, 0, null);
        public Rank rank() { return rank; }
        public Suit suit() { return suit; }
        public Image getImg() { return this.image; }
        public String toString() { return rank + " of " + suit; } 
        // Initialize prototype deck
        static {
            for (Suit suit : Suit.values()) {
                for (Rank rank : Rank.values()) {
                    String imgPath = "C:/Documents and Settings/Administrator/Desktop/java/BlackJack/" + rank + suit + ".jpg";
                    protoDeck.add(new Card(rank, suit, imgPath));
        public static LinkedList<Card> newDeck() {
            return new LinkedList<Card>(protoDeck); // Return copy of prototype deck
    import java.util.LinkedList;
    import java.util.Collections;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class BlackJack extends JFrame {
    private LinkedList<Card> deck;
    private LinkedList<Card> plCrds;
    private Card card;
    public BlackJack() {
    super();
    plCrds = new LinkedList<Card>();
    setSize(400, 500);
    deck = Card.newDeck();
    card = dealPl();
    getContentPane().add(card);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);
    public static void main(String[] args) {
    BlackJack bj = new BlackJack();
    public void paint(Graphics g) {
    g.drawImage(card.getImg(), 5, 5, this);
    private Card dealPl() {
    Card c = deck.remove();
    plCrds.add(c);
    return c;
         }

    Never override the painting methods of your top level contaier (ie. JFrame).
    Custom painting is done by overriding the paintComponent(...) method of JComponent or JPanel.
    So because you are using the Card class in a Swing application you need to extend JComponent as suggested above and override paintComponent(...), not paint(...);
    Also why do you think you even need to override any paint method to draw the cards. Just add you Cards to a panel using a null layout. Read the Swing tutorial on layout managers, specifically the section on "Absolute Positioning";
    http://java.sun.com/docs/books/tutorial/uiswing/layout/index.html
    Better yet use the appropriate combination of layout managers to get your desired look so you don't need to worry about a null layout.

  • Using JPanel with JFrame

    I am using a JFrame to encapsulate my program. I want to have a JPanel inside my JFrame to handle all of my 2d displaying (like fillRect() etc...). I used forte to set this up but I am having problems dispaying on the JPanel. Here is my code:
    here is how I call the function from the main .java file
    I dubuged this and know it works (proof will come later)
    private void Start_ButtonActionPerformed(java.awt.event.ActionEvent evt)
    myDisplay.draw();
    here is my entire JPanel class
    import java.awt.*;
    import javax.swing.*;
    public class Display extends javax.swing.JPanel
    public Display() {
    initComponents();
    public void paintComponent(Graphics g )
    System.out.println("1");
    super.paintComponent(g);
    g.setColor(Color.black);
    g.fillOval(50,10,60,60);
    public void draw()
    System.out.println("1");
    this.repaint(); //i also tried repaint() but it didn't work either
    System.out.println("2");
    private void initComponents()
    setLayout(new java.awt.BorderLayout());
    when I press the start button, 1 and 2 are displayed but 3 isn't. For some reason the repaint() function is not telling the paintComponent function to work. Any help is appreciated.
    Thanks,
    Every_man

    Every_man,
    After doing the super.paintComponent(g); you must use Graphics2D. So you next line should cast your graphics object to a graphics 2D object, like this. Graphics2D g2 = (Graphics2D)g;

  • Bug:  Histogram Does Not Update when Using Painting Tools

    I was investigating something else, and I saw something not working...  I'm under the distinct impression that the Histogram panel should automatically update after every operation.  Having the Histogram panel displayed full-time on the screen, it should always be up to date.
    However, when I Dodge or Burn or even paint color on an image, the Histogram is not updating. 
    If I select one of the History states I've just created, it updates.
    Consider this simple sequence of operations:
    I'm able to reproduce this failure in Photoshop CS5 as well, BUT NOT IN CS4 (it updates in Photoshop CS4 after every painting operation), so clearly it's not a new bug, though somehow I've managed not to notice it in my years of using Photoshop CS5.
    Is it broken like this for everyone in Photoshop CS5 and 6?
    Could this be some twisted attempt to try to optimize painting performance?  If so, why isn't there an option to allow a user to request it to update on every operation on a fast computer with cores out the wazoo?
    -Noel

    More info:
    Just poking around in Photoshop CS6 to see what, if anything would make the Histogram display update...
    Even though the Refresh icon is disabled (and the "Uncached Refresh" entry in the fly-out menu is grayed-out), double-clicking in the topmost histogram display will force it to update (as described above by Conroy in post #1 above).
    If I change the selection Channel field in the Histogram panel, mostly it does not update, but when I change between some of the settings - for example between RGB and Luminosity - the graphs update.  Amazingly they revert back to the un-updated state if I switch the channel BACK to what it was!
    Making a selection DOES cause it to update.  
    Choosing Select - Color Range (just starting the function) DOES cause it to update.
    Hitting the quick mask mode button DOES cause it to update. Notably Edit in Quick Mask Mode is in the Select menu.  Could an association with Select be a clue?
    This bug is easy to reproduce, is shown to be a problem across multiple versions and multiple OSs, and in at least one case (Photoshop CS4 x64 on Windows 7 x64 here) it can be shown to work properly, so the code is probably not far off being right.  Seems to me this should be the kind of thing a junior engineer could find and fix so someone, say,  at Chris Cox's level could have it done before 5 today... 
    -Noel

  • Using getContentPane() in JFrame class

    Hello,
    I'm reading Bruce Eckel's book.
    In chaapter 14, I read TextArea.java.
    My question is:
    What is the purpose of getContentPane() in the constructor TextArea() in the code below ?
    Isn't JFrame IS a Container ? why bother to get another Container ?
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.util.*;
    import com.bruceeckel.swing.*;
    import com.bruceeckel.util.*;
    public class TextArea extends JFrame {
    private JButton
    b = new JButton("Add Data"),
    c = new JButton("Clear Data");
    private JTextArea t = new JTextArea(20, 40);
    private Map m = new HashMap();
    public TextArea() {
    // Use up all the data:
    Collections2.fill(m, Collections2.geography,
    CountryCapitals.pairs.length);
    b.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    Iterator it = m.entrySet().iterator();
    while(it.hasNext()) {
    Map.Entry me = (Map.Entry)(it.next());
    t.append(me.getKey() + ": "+ me.getValue()+"\n");
    c.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    t.setText("");
    Container cp = getContentPane();
    cp.setLayout(new FlowLayout());
    cp.add(new JScrollPane(t));
    cp.add(b);
    cp.add(c);
    public static void main(String[] args) {
    Consoleb.run(new TextArea(), 475, 425);
    }

    I appreciate the reply.
    There are endless API to read.
    I found this:
    For conveniance JFrame, JDialog, JWindow, JApplet and
    JInternalFrame, by default, forward, by default, all
    calls to the add, remove and setLayout methods, to
    the contentPane. This means you can call:
    rootPaneContainer.add(component);That was introduced in 1.5. May people still use older versions of Java, so use that add method with caution. I myself see no reason to use it, since it is a bit of a hack.
    Another question on the side:
    How can I remove a topic that I created ?Like karma, no thread ever goes away :-)

  • 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

  • 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");

  • [b]Using audioclips in JFrame[/b]

    hey!!!!!!
    i want to know how to use audio clips in a jframe.
    i know how to use in the applet.
    plese help me with steps.

    In the future Swing related questions should be posted on the Swing forum.
    Read the tutorial on [url http://java.sun.com/docs/books/tutorial/]Sound. It highlights the differences between an applet and application.

Maybe you are looking for

  • Companionlink Google for Calendar - OR - ANY Wireless Sync Software

    I've been hacking at a way to wirelessly sync my BBerry Bold 9650 with Outlook 2007 and Google.  Since the BBerry solution offers a good email sync, there is no problem there.  Once you install Companionlink Google for BBerry it is clear that unless

  • Best Practice - existence of details

    There are many ways to manage the question of existence of details. All will work. What I am interested in is Best Practice. Example. There is a Customer table in the source, and there are Sales tables (order and detail). However, some people are rec

  • Mistake by entering figures

    Hi all! I am running Microsoft Office 2011 and Textshop as a Latex editor. When I enter data in a spreadsheet with my Keyboard, the input data will be divided by 10. Also in Textshop, when producing a .pdf file. When creating i.e. 1. Introduction 2.

  • Problem in activating after changing structure of BAPI once released

    Hi, I have created a BAPI  which is having 2 import structures. The BAPI was relaesed. When I changed component type of a field in one of the structure, it is not allowing me to re-activate it. Can we not make any changes in structure of the BAPI whe

  • Date Condition based on time

    Hi : I am working on Plant Maintenance module, i extracted work orders ( aufnr ) from AUFK based on some conditions. In the selection screen i have s_date option where the user can give any date range .my question is ...after selecting all the work o