Problems with basic Java JPanel animation using paintcomponent

okay so I am trying to animate a sprite moving across a background using a for loop within the paintComponent method of a JPanel extension
public void paintComponent(Graphics g){
Image simpleBG = new ImageIcon("Images/Backgrounds/Simple path.jpg").getImage();
Image mMan = new ImageIcon("Images/Sprites/hMan.gif").getImage();
if (!backgroundIsDrawn){
g.drawImage(simpleBG, 0, 0, this);
g.drawImage(mMan, xi, y, this);
backgroundIsDrawn=true;
else
for (int i=xi; i<500; i++){
g.drawImage(simpleBG, 0, 0, this);
g.drawImage(mMan, i, y, this);
try{
Thread.sleep(10);
} catch(Exception ex){System.out.println("damn");}
The problem is that no matter what I set my thread to, it will not show the animation, it will just jump to the last location, even if the thread sleep is set high enough that it takes several minutes to calculate,, it still does not paint the intemediary steps.
any solution, including using a different method of animation all together would be greatly appreciated. I am learning java on my own so i need all the help I can get.

fysicsandpholds1014 wrote:
even when I placed the thread sleep outside of the actual paintComponent in a for loop that called repaint(), it still did not work? Nope. Doing this will likely put the Event Dispatch Thread or EDT to sleep. Since this is the main thread that is responsible for Swing's painting and user interaction, you'll put your app to sleep with this. Again, use a Swing Timer
and is there any easy animation method that doesnt require painting and repainting every time becasue it is very hard to change what I want to animate with a single paintComponent method? I don't get this.
I find the internet tutorials either way too complicated or not nearly in depth enough. Maybe its just that I am new to programming but there doesn't seem to be a happy medium between dumbed down Swing tutorials and very complicated and sophisticated animation algorithmns.I can only advise that you practice, practice, practice. The more you use the tutorials, the easier they'll be to use.
Here's another small demo or animation. It is not optimized (repaint is called on the whole JPanel), but demonstrates some points:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.*;
@SuppressWarnings("serial")
public class AnimationDemo2 extends JPanel {
  // use a publicly available sprite for this example
  private static final String SPRITE_PATH = "http://upload.wikimedia.org/" +
            "wikipedia/commons/2/2e/FreeCol_flyingDutchman.png";
  private static final int SIDE = 600;
  private static final Dimension APP_SIZE = new Dimension(SIDE, SIDE);
  // timer delay: equivalent to the Thread.sleep time
  private static final int TIMER_DELAY = 20;
  // how far to move in x dimension with each loop of timer
  public static final int DELTA_X = 1;
  // holds our sprite image
  private BufferedImage img = null;
  // the images x & y locations
  private int imageX = 0;
  private int imageY = SIDE/2;
  public AnimationDemo2() {
    setPreferredSize(APP_SIZE);
    try {
      // first get our image
      URL url = new URL(SPRITE_PATH);
      img = ImageIO.read(url);
      imageY -= 3*img.getHeight()/4;
    } catch (Exception e) { // shame on me for combining exceptions :(
      e.printStackTrace();
      System.exit(1); // exit if fails
    // create and start the Swing Timer
    new Timer(TIMER_DELAY, new TimerListener()).start();
  // all paintComponent does is paint -- nothing else
  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.setColor(Color.blue);
    int w = getWidth();
    int h = getHeight();
    g.fillRect(0, h/2, w, h);
    if (img != null) {
      g.drawImage(img, imageX, imageY, this);
  private class TimerListener implements ActionListener {
    // is called every TIMER_DELAY ms
    public void actionPerformed(ActionEvent e) {
      imageX += DELTA_X;
      if (imageX > getWidth()) {
        imageX = 0;
      // ask JVM to paint this JPanel
      AnimationDemo2.this.repaint();
  // code to place our JPanel into a JFrame and show it
  private static void createAndShowUI() {
    JFrame frame = new JFrame("Animation Demo");
    frame.getContentPane().add(new AnimationDemo2());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  // call Swing code in a thread-safe manner
  public static void main(String[] args) {
    java.awt.EventQueue.invokeLater(new Runnable() {
      public void run() {
        createAndShowUI();
}

Similar Messages

  • Problems with basic java

    Hey all,
    Im new to this and i appericate any help you can give me:
    Im trying to ask the user for a character, and using an if statement output its (predefined) decimal equivelant. But i am having trouble, i think the if statement is fine but its reading the char into a string that im having trouble with, ANY help woudl be gREAT! thanks
    import java.io.*;
    public class prac3roman1
    public static void main(String args[]) throws IOException
              int decimal = 0;
              char numeral;
              String input_string;     
              BufferedReader myInput = new BufferedReader(new InputStreamReader(System.in));
              //System.out.print("Numeral 1: ");
              //input_string = myInput.readLine();     
              //char numeral = input_string.charAt (0);
              if (char numeral = i);
                   int decimal = 1;               
              else
                   if (char = v)
                        int decimal = 5;
                   else
                        int decimal = 10;
              System.out.println("The decimal equivelant is" + decimal);
    }

    Hi,
    Please post this to an appropriate forum. This forum is exclusively related to discussions about Sun Java Studio Creator.
    May be you can post here
    http://forum.java.sun.com/forum.jspa?forumID=31
    MJ

  • Newbie to blackberry...facing problem with basics

    hi guys,
                 i got my playbook today...........facing problem with basics
             1.how do i perform file actions(like create folder, move,rename)
             2.cant  use drag gesture
             3. ppt applications doesnt show a option to create new presentation(word and xls apps seem to work fine)
             4.can we even download apps from app world to pc  bcuz  everytime it says connect the smartphone to computer even though its physically connected and blackberry desktop manager also shows the device is connected"

    To mange your files, try a file manager like Files & Folders.
    Drag gestures are available in OS 2.0 which should be available before the end of Feb (rumour has it, this week).
    In OS 2 you will also be able to create new PPT presentations.
    To download apps from App World you need to be connected to a Wifi network at the moment.
    Files & Folders, the unified file & cloud manager for PlayBook and BB10 with SkyDrive, SugarSync, Box, Dropbox, Google Drive, Google Docs. Free 3-day trial! - Jon Webb - Innovatology - Utrecht, Netherlands

  • Solution Manager systems RAM requirements - problems with the Java Engine

    Hello,
    I am about to install SAP Solution Manager 7 on a WIndows 2003 Server x64 but I need to know what the RAM requirements are? I have been having problems with the Java Engine starting and it seems to time out, I have heard that this is a very RAM hungry process and it might be why?
    Many thanks for your help in advance,
    Omar

    Hello Omar,
    To size SAP Solution Manager 7.0 EHP1 we recommend to use the SAP Solution Manager Quicksizer Tool at:
    http://service.sap.com/sizing-solman
    Here you find information on how to use the tool, how to collect input data for E2E Scenario Sizing, on SAP E2E RCA Sizing, Introscope Tuning, Wily Enterprise Manager Cluster Setup for E2E RCA Scenario and BI Aggregation Strategy in E2E Scenario.
    Please find more information about installing Solution Manager in:
    http://service.sap.com/instguides -> SAP Solution Manager
    I hope this information helps.
    Thanks,
    Mark

  • Problem with flash on IE11 after using adobe cleaner

    Problem with flash on IE11 after using adobe cleaner to remove a trial version of photoshop because there was not any entry on add/remove applications in windows 8.1
    Its to frustrating to reinstall everything. I tried everything from your support page with no luck…

    Link for Download & Install & Setup & Activation problems may help
    -Online Chat http://www.adobe.com/support/download-install/supportinfo/

  • Problem with Adobe Premiere Elements 12 using Scary Halloween template

    I'm having a problem with Adobe Premiere Elements 12 using Scary Halloween template under Menu Theme.  My problem is the red line is default to Scenes.  I would like it to default to Play.  How can I do that? Is it a bug?
    Side Note:  Other template default to Play Movie
    Thanks

    jeffrey caban
    No bug. Just the way the .psd for the Scary Halloween template was put together.
    You are going to have to get into the .psd for the Scary Halloween template and rearrange the
    Layer Sets. Do you know how to do that? If not, I will give you very specific instructions on how to
    do that.
    You want the order of the Layer Sets to look like
    That is what worked for me just now to get the disc menu Preview to open to the main
    menu with the red highlight under Play.
    We will be watching for your reply.
    ATR

  • I have a problem with iphone4 I bought a used and unlocked iphone4 old apple id because the first owner dies please help me how to activate iphone4 I unlocked with icloud

    I have a problem with iphone4
    I bought a used and unlocked iphone4
    old apple id because the first owner dies
    please help me how to activate iphone4
    I unlocked with icloud

    fherly nur arief wrote:
    I unlocked with icloud
    If you had already removed the device from 'Find My iPhone' in iCloud, then you jus tneed to powercycle the device in order to activate it.
    Source: http://support.apple.com/kb/TS4515
    "After the device is removed from the previous owner’s account, turn the device off by pressing and holding the Sleep/Wake button located on the top-right side of the device. Then restart your device and proceed with device setup as you would normally."
    If it has not been removed, then the activation lock is still active.
    If the previous owner cannot remove the device from their account there is nothing you can do unless the place you purchased it from will give you a refund.
    Activation Lock: http://support.apple.com/kb/ht5818
    What if I purchase a device that is still linked to the previous owner's account?
    Contact the previous owner as soon as possible and ask them to erase the device and remove it from their account. For complete instructions, read how to remove a device from a previous owner's account.
    How do I check for Activation Lock before purchasing a used device?
    When purchasing an iPhone, iPad, or iPod touch from someone other than Apple or an authorized Apple reseller, it is up to you to ensure that the device has been erased and is no longer linked to the previous owner’s account.
    Follow each of these steps to make sure that you can use the device you purchase:
    Turn the device on and slide to unlock.If the passcode lock screen or the home screen appears, the device has not been erased. Ask the seller to completely erase the device by going to Settings > General > Reset > Erase All Content and Settings. Do not take ownership of any used iPhone, iPad, or iPod touch until it has been erased.
    Begin the device setup process.After choosing a language, choosing a country, and connecting to a network, the device will begin activation. If you are asked for the previous owner’s Apple ID and password, the device is still linked to their account. Hand the device back to the seller and ask them to enter their password. If the previous owner is not present, they can remove the device from their account by signing in to icloud.com/find. Do not take ownership of any used iPhone, iPad, or iPod touch until it has been removed from the previous owner’s account.
    You will know that a device is ready for you to use when you are asked to “Set up your iPhone", “Set up your iPad", or “Set up your iPod” during the device setup process.

  • I have the new iPad. Even with airplane mode on, my battery life is extremely limited. Is there a problem with the battery? I used to have the ipad2 and had no such problem.

    I have the new iPad. Even with airplane mode on, my battery life is extremely limited. Is there a problem with the battery? I used to have the ipad2 and had no such problem.

    What is your brightness setting & how many apps are open?
    The quickest way (and really the only way) to charge your iPad is with the included 10W USB Power Adapter. iPad will also charge, although more slowly, when attached to a computer with a high-power USB port (many recent Mac computers) or with an iPhone Power Adapter (5W). When attached to a computer via a standard USB port (most PCs or older Mac computers) iPad will charge very slowly (but iPad indicates not charging). Make sure your computer is on while charging iPad via USB. If iPad is connected to a computer that’s turned off or is in sleep or standby mode, the iPad battery will continue to drain.
    Apple recommends that once a month you let the iPad fully discharge & then recharge to 100%.
    How to Calibrate Your Mac, iPhone, or iPad Battery
    http://www.macblend.com/how-to-calibrate-your-mac-iphone-or-ipad-battery/
    At this link http://www.tomshardware.com/reviews/galaxy-tab-android-tablet,3014-11.html , tests show that the iPad 2 battery (25 watt-hours) will charge to 90% in 3 hours 1 minute. It will charge to 100% in 4 hours 2 minutes. The new iPad has a larger capacity battery (42 watt-hours), so using the 10W charger will obviously take longer. If you are using your iPad while charging, it will take even longer. It's best to turn your new iPad OFF and charge over night. Also look at The iPad's charging challenge explained http://www.macworld.com/article/1150356/ipadcharging.html
    Also, if you have a 3rd generation iPad, look at
    Apple: iPad Battery Nothing to Get Charged Up About
    http://allthingsd.com/20120327/apple-ipad-battery-nothing-to-get-charged-up-abou t/
    Apple Explains New iPad's Continued Charging Beyond 100% Battery Level
    http://www.macrumors.com/2012/03/27/apple-explains-new-ipads-continued-charging- beyond-100-battery-level/
    New iPad Takes Much Longer to Charge Than iPad 2
    http://www.iphonehacks.com/2012/03/new-ipad-takes-much-longer-to-charge-than-ipa d-2.html
    Apple Batteries - iPad http://www.apple.com/batteries/ipad.html
    Extend iPad Battery Life (Look at pjl123 comment)
    https://discussions.apple.com/thread/3921324?tstart=30
    New iPad Slow to Recharge, Barely Charges During Use
    http://www.pcworld.com/article/252326/new_ipad_slow_to_recharge_barely_charges_d uring_use.html
    Tips About Charging for New iPad 3
    http://goodscool-electronics.blogspot.com/2012/04/tips-about-charging-for-new-ip ad-3.html
    Prolong battery lifespan for iPad / iPad 2 / iPad 3: charging tips
    http://thehowto.wikidot.com/prolong-battery-lifespan-for-ipad
    In rare instances when using the Camera Connection Kit, you may notice that iPad does not charge after using the Camera Connection Kit. Disconnecting and reconnecting the iPad from the charger will resolve this issue.
     Cheers, Tom

  • JCoIDoc IDocLibrary 3.0.2 Problems with IDocServerExample.java

    Hello, I´m facing a problem with IDocServerExample.java. I created a new project in eclipse, added the package com.sap.conn.idoc.examples and the class IDocServerExample.java. I configured the files "MYSERVER.jcoServer" and "BCE.jcoDestination" and started the application. Then I get the following error messages: *********************************************************************************************************************************************************
    com.sap.conn.jco.JCoException: (102) RFC_ERROR_COMMUNICATION: Unable to get repository at com.sap.conn.jco.rt.DefaultServer.update(DefaultServer.java:136) at com.sap.conn.jco.rt.DefaultServer.(DefaultServer.java:105) at com.sap.conn.idoc.jco.DefaultJCoIDocServer.(DefaultJCoIDocServer.java:35) at com.sap.conn.idoc.jco.DefaultJCoIDocServerFactory.createServer(DefaultJCoIDocServerFactory.java:17) at com.sap.conn.idoc.jco.DefaultJCoIDocServerFactory.createServer(DefaultJCoIDocServerFactory.java:13) at com.sap.conn.jco.rt.DefaultServerManager.getServer(DefaultServerManager.java:108) at com.sap.conn.jco.rt.StandaloneServerFactory.getServerInstance(StandaloneServerFactory.java:170) at com.sap.conn.idoc.jco.JCoIDoc.getServer(JCoIDoc.java:78) at com.sap.conn.idoc.examples.IDocServerExample.main(IDocServerExample.java:18) Caused by: com.sap.conn.jco.JCoException: (102) RFC_ERROR_COMMUNICATION: Connect to message server host failed Connection parameters: TYPE=B DEST=JCOSERVER01 MSHOST=arm115tx GROUP=PUBLIC R3NAME=T01 PCS=1 LOCATION CPIC (TCP/IP) on local host rz1462 with Unicode ERROR service '?' unknown TIME Tue Jul 07 09:09:40 200 RELEASE 711 COMPONENT NI (network interface) VERSION 39 RC -3 DETAIL NiErrSet COUNTER 2 at com.sap.conn.jco.rt.MiddlewareJavaRfc.generateJCoException(MiddlewareJavaRfc.java:615) at com.sap.conn.jco.rt.MiddlewareJavaRfc$JavaRfcClient.connect(MiddlewareJavaRfc.java:1280) at com.sap.conn.jco.rt.ClientConnection.connect(ClientConnection.java:661) at com.sap.conn.jco.rt.PoolingFactory.init(PoolingFactory.java:103) at com.sap.conn.jco.rt.ConnectionManager.createFactory(ConnectionManager.java:171) at com.sap.conn.jco.rt.DefaultConnectionManager.createFactory(DefaultConnectionManager.java:44) at com.sap.conn.jco.rt.ConnectionManager.getFactory(ConnectionManager.java:160) at com.sap.conn.jco.rt.RfcDestination.initialize(RfcDestination.java:789) at com.sap.conn.jco.rt.RfcDestination.getSystemID(RfcDestination.java:817) at com.sap.conn.jco.rt.RepositoryManager.getRepository(RepositoryManager.java:32) at com.sap.conn.jco.rt.RfcDestination.getRepository(RfcDestination.java:891) at com.sap.conn.jco.rt.DefaultServer.update(DefaultServer.java:132) ... 8 more Caused by: RfcException: [null] message: Connect to message server host failed Connection parameters: TYPE=B DEST=JCOSERVER01 MSHOST=arm115tx GROUP=PUBLIC R3NAME=T01 PCS=1 LOCATION CPIC (TCP/IP) on local host rz1462 with Unicode ERROR service '?' unknown TIME Tue Jul 07 09:09:40 200 RELEASE 711 COMPONENT NI (network interface) VERSION 39 RC -3 DETAIL NiErrSet COUNTER 2 Return code: RFC_FAILURE(1) error group: 102 key: RFC_ERROR_COMMUNICATION at com.sap.conn.rfc.engine.RfcIoControl.error_end(RfcIoControl.java:255) at com.sap.conn.rfc.engine.RfcIoControl.ab_rfcopen(RfcIoControl.java:94) at com.sap.conn.rfc.api.RfcApi.RfcOpen(RfcApi.java:83) at com.sap.conn.jco.rt.MiddlewareJavaRfc$JavaRfcClient.connect(MiddlewareJavaRfc.java:1273) ... 18 more
    Does anyone know what I´m doing wrong? With thanks, Veit

    Im having the same issue here.  Has anyone found a solution to this?

  • We encountered a problem with some client machines that use Firefox version 24ESR and IE8. Ajax requests of aspx pages from Firefox are getting the following er

    I encountered a problem with some client machines that use Firefox version 24ESR and IE8.
    Ajax requests of aspx pages from Firefox are getting the following error from the iis server (iis version 7.5):
    Bad Request - Request Too Long
    HTTP Error 400. The size of the request headers is too long.
    From analyzing the request that was sent to the server, I saw that the request consist of only the viewstate of the aspx page.
    I tried to disable the viewstate for one page and the server got the request correctly.
    I do not encounter any issues on these laptops with postback requests from Firefox or when running the same application with IE8.

    Sometimes that means that the page address sent is loo long.
    Check the link address you are using.
    I can't help you further and will send for more help.

  • Problem with too small page size using Java 2D Printing API.

    Hello,
    I have problem with resolution of printer using Java 2D Printing API. Despite my printer has 600 x 600 DPI, inside java.awt.print.Printable.print(Graphics, PageFormat, int) I receive page format with 600 x 840 page size.
    I have tried to set resolution using javax.print.attribute.PrintRequestAttributeSetand javax.print.attribute.standard.PrinterResolution, but with no result.
    Can anybody solve this problem?
    Regards,
    Karl.

    600 x 840 is a Point value; Point is defined as 1/72nd of an inch. Printers do have much higher DPI than this, but I believe that this DPI has to do with richness of the printed image, not an actual ability to color with that level of resolution. You might want to try calling zoom on your Graphics2D object. Otherwise, I don't know what else you can try.

  • Problem with multiple transparent JPanels

    Hi,
    I'm currently trying to implement some kind of message box that can fade in and out. This message box is a subclass of JComponent, the message it contains can be an arbitrary Swing-Component.
    The message container and the message itself have the same background color. When fading, the (partly transparent) colors of the of the container and the message are added, which I do not want.
    Here are two images to illustrate my problem:
    What I have: http://www.inf.tu-dresden.de/~ab023578/javaforum/reality.gif
    What I want: http://www.inf.tu-dresden.de/~ab023578/javaforum/wish.gif
    Here is the code:
    import java.awt.*;
    import javax.swing.*;
    public class Main {
        static float transparency = 0f;
        public static void main(String[] args) {
            JPanel jpBack = new JPanel() {
                protected void paintComponent(Graphics g) {
                    Graphics2D g2d = (Graphics2D)g;
                    g2d.clearRect(0, 0, getWidth(), getHeight());
                    g2d.setColor(getBackground());
                    AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, transparency);
                    g2d.setComposite(alpha);
                    g2d.fillRect(0, 0, getWidth(), getHeight());
            jpBack.setBackground(Color.WHITE);
            jpBack.setLayout(null);
            JPanel jpContainer = new JPanel();
            jpContainer.setBackground(Color.RED);
            jpContainer.setLayout(null);
            JPanel jpMessage = new JPanel();
            jpMessage.setBackground(Color.RED);
            JLabel jlMessage = new JLabel("MESSAGE");
            jpBack.add(jpContainer);
            jpContainer.add(jpMessage);
            jpMessage.add(jlMessage);
            jpContainer.setBounds(10, 10, 120, 100);
            jpMessage.setBounds(10, 10, 100, 50);
            JFrame frame = new JFrame();
            frame.setBounds(0, 0, 150, 150);
            frame.setBackground(Color.WHITE);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(jpBack);
            frame.setVisible(true);
            for (double a = 0; true; a += 0.01D) {
                try {
                    Thread.sleep(10);
                catch (InterruptedException e) {}
                transparency = (float)Math.abs(Math.sin(a));
                jpBack.repaint();
    }I understand that the Porter-Duff-Rule SRC_OVER causes the container to be drawn over the message (or vice versa) and both of them over the background. I think what I need is a way to handle the whole jpContainer-Panel and all its subcomponents as a single source image. Is that possible?

    Thank you for your answer, Sarcommand. Unfortunately the test program I provided is a bit too simple as your solution works here but not for my original problem. :|
    Let me explain what I want to achieve and why.
    I'm writing a tool for algorithm visualisation. Currently I am dealing with a parsing algorithm (having compontents such as an automaton with an input tape, output tape and a stack). Those components (containers) can contain multiple JComponents (GraphicalObjects), which display a BufferedImage that can be altered during the animation.
    I want to create my message windows the same way. A container that contains GraphicalObjects (or, if necessary, any other Swing component). One GraphicalObject has a very limited field of responsibility: mereley displaying its information.
    Aligning the GraphicalObject is one of the container's responsibilities.
    What I'm currently trying to do is to put my GraphicalMessage into the center of a container, leaving an offset on the left/right/upper/lower side. This is why I need the same background color for both the GraphicalMessage and the MessageContainer, I don't want the user to see that there are actually two JComponents on top of each other.
    While I could use another approach for text messages I prefer this one as I would be able to fade arbitrary Containers and their GraphicalObjects .
    Here is the code:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.image.BufferedImage;
    public class Main {
        static float transparency = 0f;
        public static void main(String[] args) {
            JPanel jpBack = new JPanel() {
                protected void paintComponent(Graphics g) {
                    Graphics2D g2d = (Graphics2D)g;
                    g2d.clearRect(0, 0, getWidth(), getHeight());
                    g2d.setColor(getBackground());
                    AlphaComposite alpha = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, transparency);
                    g2d.setComposite(alpha);
                    g2d.fillRect(0, 0, getWidth(), getHeight());
                    super.paintComponent(g);
            jpBack.setBackground(Color.WHITE);
            jpBack.setLayout(null);
            JPanel jpContainer = new JPanel();
            jpContainer.setBackground(Color.RED);
            jpContainer.setLayout(null);
            GraphicalMessage msg = new GraphicalMessage();
            jpBack.add(jpContainer);
            jpContainer.add(msg);
            jpContainer.setBounds(10, 10, 120, 100);
            msg.setBounds(10, 10, 160, 60);
            JFrame frame = new JFrame();
            frame.setBounds(0, 0, 150, 150);
            frame.setBackground(Color.WHITE);
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(jpBack);
            frame.setVisible(true);
            float stepSize = 0.01f;
            float step = stepSize;
            for (float a = 0; true; a += step) {
                try {
                    Thread.sleep(10);
                catch (InterruptedException e) {}
                if (a >= 1) {
                    step = -stepSize;
                    a -= stepSize;
                if (a <= 0) {
                    step = stepSize;
                    a += stepSize;
                    msg.updateInternalContent();
                    msg.redraw();
                transparency = a;
                jpBack.repaint();
    class GraphicalMessage extends JComponent {
        private String text;
        private Graphics2D ig2d;
        private BufferedImage image;
        public GraphicalMessage() {
            setLayout(null);
            image = new BufferedImage(100, 50, BufferedImage.TYPE_INT_ARGB);
            ig2d = image.createGraphics();
            ig2d.setColor(Color.BLACK);
            ig2d.setBackground(Color.RED);
            ig2d.setFont(new Font("Courier New", Font.BOLD, 20));
            updateInternalContent();
            redraw();
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D)g;
            g2d.drawImage(image, 0, 0, null);
        public void redraw() {
            ig2d.clearRect(0, 0, image.getWidth(), image.getHeight());
            ig2d.drawString(text, 0, 20);
        public void updateInternalContent() {
            text = String.valueOf((int)(Math.random() * 10000));
    }A possibility to erase the text from the BufferedImage without having to draw a rectangle would help me as well.

  • Advance level drawing problem with Jframe and JPanel need optimize sol?

    Dear Experts,
    I m trying to create a GUI for puzzle game following some kind of "game GUI template", but i have problems in that,so i tried to implement that in various ways after looking on internet and discussions about drawing gui in swing, but i have problem with both of these, may be i m doing some silly mistake, which is still out of my consideration. please have a look at these two and recommend me one of them, which is running without problems (flickring and when you enlarge window the board draw copies (tiled) everywhere,
    Note: i don't want to inherit jpanel or Jframe
    here is my code : import java.awt.BorderLayout;
    public class GameMain extends JFrame {
         private static final long serialVersionUID = 1L;
         public int mX, mY;
         int localpoints = 0;
         protected static JTextField[][] squares;
         protected JLabel statusLabel = new JLabel("jugno");
         Label lbl_score = new Label("score");
         Label lbl_scorelocal = new Label("local score");
         protected static TTTService remoteTTTBoard;
         // Define constants for the game
         static final int CANVAS_WIDTH = 800; // width and height of the game screen
         static final int CANVAS_HEIGHT = 600;
         static final int UPDATE_RATE = 4; // number of game update per second
         static State state; // current state of the game
         private int mState;
         // Handle for the custom drawing panel
         private GameCanvas canvas;
         // Constructor to initialize the UI components and game objects
         public GameMain() {
              // Initialize the game objects
              gameInit();
              // UI components
              canvas = new GameCanvas();
              canvas.setPreferredSize(new Dimension(CANVAS_WIDTH, CANVAS_HEIGHT));
              this.setContentPane(canvas);
              this.setDefaultCloseOperation(EXIT_ON_CLOSE);
              this.pack();
              this.setTitle("MY GAME");
              this.setVisible(true);
         public void gameInit() {     
         // Shutdown the game, clean up code that runs only once.
         public void gameShutdown() {
         // To start and re-start the game.
         public void gameStart() {
         private void gameLoop() {
         public void keyPressed(KeyEvent e) {
         public void keyTyped(KeyEvent e) {
         public void gameKeyReleased(KeyEvent e) {
              PuzzleBoard bd = getBoard();
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        if (e.getSource() == squares[row][col]) {
                             if (bd.isOpen(col, row)) {
                                  lbl_score.setText("Highest Score = "
                                            + Integer.toString(bd.getPoints()));
                                  setStatus1(bd);
                                  pickSquare1(col, row, squares[row][col].getText()
                                            .charAt(0));
         protected void pickSquare1(int col, int row, char c) {
              try {
                   remoteTTTBoard.pick(col, row, c);
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
         // method "called" by remote object to update the state of the game
         public void updateBoard(PuzzleBoard new_board) throws RemoteException {
              String s1;
              for (int row = 0; row < 4; ++row) {
                   for (int col = 0; col < 4; ++col) {
                        squares[row][col].setText(new_board.ownerStr(col, row));
              lbl_score.setText("Highest Score = "
                        + Integer.toString(new_board.getPoints()));
              setStatus1(new_board);
         protected void setStatus1(PuzzleBoard bd) {
              boolean locals = bd.getHave_winner();
              System.out.println("local win" + locals);
              if (locals == true) {
                   localpoints++;
                   System.out.println("in condition " + locals);
                   lbl_scorelocal.setText("Your Score = " + localpoints);
              lbl_score
                        .setText("Highest Score = " + Integer.toString(bd.getPoints()));
         protected PuzzleBoard getBoard() {
              PuzzleBoard res = null;
              try {
                   res = remoteTTTBoard.getState();
              } catch (RemoteException e) {
                   System.out.println("Exception: " + e.getMessage());
                   e.printStackTrace();
                   System.exit(1);
              return res;
         /** Custom drawing panel (designed as an inner class). */
         class GameCanvas extends JPanel implements KeyListener {
              /** Custom drawing codes */
              @Override
              public void paintComponent(Graphics g) {
                   // setOpaque(false);
                   super.paintComponent(g);
                   // main box; everything placed in this
                   // JPanel box = new JPanel();
                   setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
                   // add(statusLabel, BorderLayout.NORTH);
                   // set up the x's and o's
                   JPanel xs_and_os = new JPanel();
                   xs_and_os.setLayout(new GridLayout(5, 5, 0, 0));
                   squares = new JTextField[5][5];
                   for (int row = 0; row < 5; ++row) {
                        for (int col = 0; col < 5; ++col) {
                             squares[row][col] = new JTextField(1);
                             squares[row][col].addKeyListener(this);
                             if ((row == 0 && col == 1) || (row == 2 && col == 3)
                             || (row == 1 && col == 4) || (row == 4 && col == 4)
                                       || (row == 4 && col == 0))
                                  JPanel p = new JPanel(new BorderLayout());
                                  JLabel label;
                                  if (row == 0 && col == 1) {
                                       label = new JLabel("1");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4 && col == 0) {// for two numbers or
                                       // two
                                       // blank box in on row
                                       label = new JLabel("2");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 1 && col == 4) {
                                       label = new JLabel("3");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else if (row == 4) {
                                       label = new JLabel("4");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  else {
                                       label = new JLabel("5");
                                       label.setHorizontalAlignment(JLabel.LEFT);
                                       label.setVerticalAlignment(JLabel.TOP);
                                  label.setOpaque(true);
                                  label.setBackground(squares[row][col].getBackground());
                                  label.setPreferredSize(new Dimension(label
                                            .getPreferredSize().width, squares[row][col]
                                            .getPreferredSize().height));
                                  p.setBorder(squares[row][col].getBorder());
                                  squares[row][col].setBorder(null);
                                  p.add(label, BorderLayout.WEST);
                                  p.add(squares[row][col], BorderLayout.CENTER);
                                  xs_and_os.add(p);
                             } else if ((row == 2 && col == 1) || (row == 1 && col == 2)
                                       || (row == 3 && col == 3) || (row == 0 && col == 3)) {
                                  xs_and_os.add(squares[row][col]);
                                  // board[ row ][ col ].setEditable(false);
                                  // board[ row ][ col ].setText("");
                                  squares[row][col].setBackground(Color.RED);
                                  squares[row][col].addKeyListener(this);
                             } else {
                                  squares[row][col] = new JTextField(1);
                                  // squares[row][col].addActionListener(this);
                                  squares[row][col].addKeyListener(this);
                                  xs_and_os.add(squares[row][col]);
                   this.add(xs_and_os);
                   this.add(statusLabel);
                   this.add(lbl_score);
                   this.add(lbl_scorelocal);
              public void keyPressed(KeyEvent e) {
              public void keyReleased(KeyEvent e) {
                   gameKeyReleased(e);
              public void keyTyped(KeyEvent e) {
         // main
         public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                   @Override
                   public void run() {
                        new GameMain();
      thanks a lot for your time , consideration and efforts.
    jibby
    Edited by: jibbylala on Sep 20, 2010 6:06 PM

    jibbylala wrote:
    thanks for mentioning as i wasn't able to write complete context here.Yep thanks camickr. I think that Darryl's succinct reply applies here as well.

  • Encountering Problems with Basic Sound Tutorial

    Hello everyone,
    I am encountering problems with a basic sound tutorial. I am absolutely confused as to what the problem may be because the code is so simple, and is essentially copied from the textbook. I am convinced that I have done something very silly but cannot see it.
    I have attempted to run this in an appletviewer, Firefox and Internet Explorer. I have attempted to launch it from both a .class file and a .jar file. I have uninstalled and offline installed the JDK and JRE and successfully tested the new installations.
    The audio file I am attempting to load and play is an .AU (Sun/Next 8-bit u-law) audio file I created in Audacity. It is located in the same folder as the AudioApplet.class file.
    My sound system is defintely on, since I have listened to music all day. I have attempted running the program with Media Player closed.
    package edu.myuniversityid.sandbox;
    import java.applet.Applet;
    import java.applet.AudioClip;
    * @author Ibuki
    public class AudioApplet extends Applet
         * Initialization method that will be called after the applet is loaded
         * into the browser.
        public void init()
            super.init();
            AudioClip ac = this.getAudioClip(this.getDocumentBase(), "sample.au");
            ac.play();
    }The code compiles fine, however absolutely I get a small white window when it is run. No sound.
    Thankyou for your time.
    Regards,
    Ibuki.
    PS. I am sure this worked before the university forced me to update my version of Windows to SP2. Hence, the reason for reinstalling Java. Twice.
    Edited by: Ibuki on Jan 31, 2008 11:09 AM becasuse: Added a PS.

    I have attempted this alternative, without success:
        public void init()
            try
                super.init();
                URL url = new URL(this.getDocumentBase(), "sample.au");
                AudioClip ac = this.getAudioClip(url);
                ac.play();
            catch (MalformedURLException ex)
                Logger.getLogger(AudioApplet.class.getName()).log(Level.SEVERE, null, ex);
        }The sample.au is definetly in the correct directory. Both File Explorer and NetBeans confirm this.
    Edited by: Ibuki on Jan 31, 2008 11:59 AM
    I have discovered a temporary solution that works in the applet viewer. The applet will load and plays the correct music perfectly. However, using this code it is not working when I try to deploy it using a web browser (MSIE and FF)!
    public void init()
            super.init();
            AudioClip ac = this.getAudioClip(this.getClass().getResource("sample.au"));
            ac.play();
    Edited by: Ibuki on Jan 31, 2008 12:12 PM
    Eureka!
    Having worked in the applet viewer I managed to get it working in the web browser by simply packaging my SoundApplet.class and sample.au into a .jar archive.
    <html>
         <body>
              <applet code="edu.myuniversityid.sandbox.AudioApplet.class" archive="dist/AudioApplet.jar">Unfortunately, this applet content cannot be displayed on this web page because your current browser does not support Java SE 6! Please <a href="http://www.java.com/">update your version of Java</a>.</applet>
         </body>
    </html>
    public void init()
            super.init();
            AudioClip ac = this.getAudioClip(this.getClass().getResource("sample.au"));
            ac.play();
        }Thankyou everyone.
    This thread can be closed if applicable. I'm not aware of the current moderation policy on this forum.
    Edited by: Ibuki on Jan 31, 2008 12:12 PM

  • Problem with Graphics and JPanel...

    I would like to draw a rectangle on a JPanel. Here is my code:
    JPanel panel = new JPanel();
    Graphics g = panel.getGraphics();
    g.drawRect(20,20,20,20);
    When I run my program, I have a NullPointerException...
    Do you any suggestions to fix the problem??
    thanks
    Pete

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    public class pete extends JFrame {
      public pete() {
        JPanel panel = new JPanel() {
          public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            int midx = getSize().width / 2;
            int midy = getSize().height / 2;
            g2.draw(new Rectangle2D.Double(midx/2, midy/2, midx, midy));
        getContentPane().add(panel, "Center");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(400,300);
        setLocation(300,100);
        setVisible(true);
      public static void main(String[] args) {
        new pete();
    }

Maybe you are looking for

  • HP Recovery Disc Creation Error

    I just bought a new HP Pavilion 500 desktop AMD Elite Quad Core A8-6500 8GB memory 2TB hd, and I am trying to create recovery discs as recommended by the system using DVD+R (Memorex Brand) discs to complete this process. The program comes up, checks

  • How do I get Thunderbird to show Date for email intead of just Time?

    New Mail only shows Time. Seems to have started with change to 2015

  • Data no getting populated from input help to target field

    Hi , I have made a input help for a field. and have used the following code to populte the data into the input help.I am having the data displayed but the data doesnot get populated on selection. CASE cs_dropdownlb_data-fieldname.       WHEN 'ZZSALSP

  • Performance issue in ALV

    Hi I have performance problem while calling an ALV function module: the code is as follows: call function 'REUSE_ALV_GRID_DISPLAY'           exporting             i_callback_program      = 'SAPLZIIS_WSTRAT'             i_callback_user_command = 'USER

  • Camera shutter doesn't open

    The shutter will not open on my iphone camera. It works fine if I switch to the front-facing camera, but when I switch back to the rear camera the shutter is closed. The same thing happens in instagram. I have closed the camera app. I have done a res