473,653 Members | 2,968 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Trouble with animation

23 New Member
I am currently working on a GUI. The idea is that when the user clicks a given button, that portion of the interface will slide into view from the main JFrame. The code I have written and included constitutes an initial test at the basic mechanics of animation. Everything works alright with my code, but the animation seems choppy. Any tips or tricks regarding good Java animation are very much appreciated.

Here is my code:
Expand|Select|Wrap|Line Numbers
  1.  import java.awt.*;
  2.    import java.awt.geom.*;
  3.    import java.awt.event.*;
  4.    import java.awt.image.*;
  5.    import javax.swing.*;
  6.  
  7.     public class AniTest
  8.    {
  9.        public static void main( String[] args )
  10.       {
  11.          AniFrame frame = new AniFrame();
  12.          frame.display();
  13.       }
  14.    }
  15.  
  16.     class AniFrame extends JFrame implements ActionListener
  17.    {
  18.       private JButton btnOpen;
  19.       private JButton btnClose;
  20.       private JButton btnExit;
  21.       private JPanel panelButton;
  22.       private JPanel aniPanel;
  23.       private OpenThread openThread;
  24.       private CloseThread closeThread;
  25.  
  26.        public AniFrame()
  27.       {
  28.          btnOpen = new JButton( "Open" );
  29.          btnOpen.addActionListener( this );
  30.  
  31.          btnClose = new JButton( "Close" );
  32.          btnClose.addActionListener( this );
  33.  
  34.          btnExit = new JButton( "Exit" );
  35.          btnExit.addActionListener( 
  36.                 new ActionListener(){
  37.                    public void actionPerformed( ActionEvent e )
  38.                   {
  39.                      System.exit( 0 );
  40.                   }
  41.                });
  42.  
  43.           //set up panel
  44.          panelButton = new JPanel();
  45.          panelButton.add( btnOpen );
  46.          panelButton.add( btnClose );
  47.          panelButton.add( btnExit );
  48.          panelButton.setBorder( BorderFactory.createMatteBorder( 3, 3, 3, 3, Color.BLACK ) );
  49.  
  50.          aniPanel = new JPanel();
  51.          aniPanel.setBorder( BorderFactory.createMatteBorder( 0, 1, 1, 1, Color.RED ) );
  52.  
  53.           //set up this
  54.          setUndecorated( true );
  55.          setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
  56.          setLayout( new BorderLayout() );
  57.          add( panelButton, BorderLayout.NORTH );
  58.          add( aniPanel, BorderLayout.CENTER );
  59.          pack();
  60.          setLocationRelativeTo( null );
  61.       }
  62.    //==================================================================================
  63.        public void display()
  64.       {
  65.          setVisible( true );
  66.       }
  67.    //==================================================================================
  68.        private BufferedImage getDialogAsImage( JComponent source )
  69.       {
  70.          BufferedImage offscreenImage;
  71.  
  72.          GraphicsConfiguration gfxConfig =
  73.             GraphicsEnvironment.getLocalGraphicsEnvironment( )
  74.                    .getDefaultScreenDevice( )
  75.                    .getDefaultConfiguration( );
  76.          offscreenImage =
  77.             gfxConfig.createCompatibleImage(source.getWidth( ),
  78.                                 source.getHeight( )); 
  79.          Graphics2D offscreenGraphics =
  80.             (Graphics2D) offscreenImage.getGraphics( );
  81.          source.paint (offscreenGraphics);
  82.  
  83.          return offscreenImage;
  84.       }
  85.    //==================================================================================
  86.        public void actionPerformed( ActionEvent e )
  87.       {
  88.          JButton btn = (JButton)e.getSource();
  89.          if( btn == btnOpen )
  90.             (new OpenThread( this, aniPanel, getDialogAsImage(
  91.                    (JComponent)((new MyOpenDialog()).getOpenDialog().getContentPane()) ) )).start();
  92.          else
  93.             (new CloseThread( this, aniPanel, getDialogAsImage(
  94.                    (JComponent)((new MyOpenDialog()).getOpenDialog().getContentPane()) ) )).start();
  95.          repaint();
  96.       }
  97.    //==================================================================================   
  98.        class OpenThread extends Thread
  99.       {
  100.          private JFrame frame;
  101.          private JPanel panel, panelTemp;
  102.          private BufferedImage image, imageTemp;
  103.  
  104.           public OpenThread( JFrame frame, JPanel panel, BufferedImage image )
  105.          {
  106.             this.frame = frame;
  107.             this.panel = panel;
  108.             this.image = image;
  109.          }
  110.           public void run()
  111.          {
  112.             int width = image.getWidth();
  113.             int height = image.getHeight();
  114.             int heightStep = (int)( height / 20 );
  115.             int currentHeight = 0;
  116.  
  117.             for( int count = 0; count < 20; count++ )
  118.             {
  119.                panel.removeAll();
  120.                currentHeight += heightStep;
  121.                imageTemp = image.getSubimage( 0, (height - currentHeight), width, currentHeight );
  122.                panelTemp = 
  123.                    new JPanel(){
  124.                       public void paintComponent( Graphics g )
  125.                      {
  126.                         super.paintComponent( g );
  127.                         Graphics2D g2d = (Graphics2D)g;
  128.                         g.drawImage( imageTemp, 0, 0, null );
  129.                      }
  130.                   };
  131.                panelTemp.setPreferredSize( new Dimension( 
  132.                           imageTemp.getWidth(), imageTemp.getHeight() ) );
  133.                panel.add( panelTemp );
  134.                frame.pack();
  135.                try{ Thread.sleep( 5 ); }
  136.                    catch( InterruptedException ie ) {}
  137.             }
  138.  
  139.             panelTemp.add( (new MyOpenDialog()).getOpenDialog().getContentPane() );
  140.             panel.revalidate();
  141.             frame.pack();
  142.          }
  143.       }
  144.    //==================================================================================
  145.        class CloseThread extends Thread
  146.       {
  147.          private JFrame frame;
  148.          private JPanel panel, panelTemp;
  149.          private BufferedImage image, imageTemp;
  150.  
  151.           public CloseThread( JFrame frame, JPanel panel, BufferedImage image )
  152.          {
  153.             this.frame = frame;
  154.             this.panel = panel;
  155.             this.image = image;
  156.          }
  157.           public void run()
  158.          {   
  159.             int width = image.getWidth();
  160.             int height = image.getHeight();
  161.             int heightStep = (int)( height / 20 );
  162.             int currentHeight = 0;
  163.  
  164.             for( int count = 0; count < 20; count++ )
  165.             {
  166.                panel.removeAll();
  167.                currentHeight += heightStep;
  168.                imageTemp = image.getSubimage( 0, currentHeight, width, (height - currentHeight) );
  169.                panelTemp = 
  170.                    new JPanel(){
  171.                       public void paintComponent( Graphics g )
  172.                      {
  173.                         super.paintComponent( g );
  174.                         Graphics2D g2d = (Graphics2D)g;
  175.                         g.drawImage( imageTemp, 0, 0, null );
  176.                      }
  177.                   };
  178.                panelTemp.setPreferredSize( new Dimension( 
  179.                           imageTemp.getWidth(), imageTemp.getHeight() ) );
  180.                panel.add( panelTemp );
  181.                frame.pack();
  182.                try{ Thread.sleep( 5 ); }
  183.                    catch( InterruptedException ie ) {}
  184.             }
  185.  
  186.             panelTemp.add( (new MyOpenDialog()).getOpenDialog().getContentPane() );
  187.             panel.revalidate();
  188.             frame.pack();  
  189.          }
  190.       }
  191.    }
  192. //==================================================================================
  193.     class MyOpenDialog extends JFileChooser
  194.    {
  195.        public JDialog getOpenDialog()
  196.       {
  197.          setDialogType( JFileChooser.OPEN_DIALOG );
  198.          return createDialog( null );
  199.       }
  200.    }
  201. //==================================================================================
  202.  
Mar 5 '09 #1
0 1507

Sign in to post your reply or Sign up for a free account.

Similar topics

0
1310
by: Simena Dinas | last post by:
KToon: 2D Animation Toolkit KToon is a 2D Animation Toolkit designed by animators (Toonka Films) for animators, focused to the Cartoon's industry. This project is covered by the GPL License using G++, OpenGL and QT as programming resources from KDevelop as the development platform. One year later of production, it is a pleasure for Toonka Films announces to the Free Software community the release of the KToon
5
3445
by: Brian Angliss | last post by:
I'm relatively new to scripting in JavaScript, so I'm not too surprised I'm having difficulty scripting up an animation effect for my personal site. What I'm trying to do is the following: When I go onMouseOver on a button in a nav bar, I want that button to switch to a different image while at the same time another blank image changes as an animation to an associated image. When I go onMouseOut, the bar image reverts back to the...
6
2392
by: Darren | last post by:
X-No-Archive Hi all, Can anyone help me with structuring the data in a small tool I have to build? I'm trying to work out if there's a design pattern or data structure that would remove some of the dependencies. I am designing an animation tool.
3
2081
by: James | last post by:
Hello, I'm new to c# and have created an animation which draws directly to the window, it uses the code below which all works. I would like to know if this is the 'correct' way to do it - or would an experienced c# programmer do it another way? This part defines the screen and the graphics pad I'm drawing to: Graphics screen = CreateGraphics(); Graphics drawpadg = Graphics.FromImage(drawpad);
10
2287
by: Robert Skidmore | last post by:
Take a look at this new JS function I made. It is really simple but very powerful. You can animate any stylesheet numeric value (top left width height have been tested), and works for both % and px values. Works in both ie and firefox. Parameters styleType = top | left | width | height toNumber = the new value of the style then you pass in as many ids as you would like.
3
7160
by: weston | last post by:
I'm making a foray into trying to create custom vertical scrollbars and sliders, and thought I had a basic idea how to do it, but seem to be having some trouble with the implementation. My thinking was: (a) create a div for the slider / scroll nub to move within (b) attach event handlers which, onmousedown, specify the slider/nub is moveable, and onmouseup, specify it's not (c) attach an event handler to the contaning div which,...
4
2785
by: petermichaux | last post by:
Hi, Is there any way to make DOM scripted animation smoother? Flash is far superior in this area. Any one here know what makes Flash so smooth by comparison? I don't like the fact that the standards based world is so far behind the Flash based stuff in some areas (animation and server push in particular)
2
1834
by: jasonchan | last post by:
I am trying to have a function start with a timer and then switch to another function. However, it is not working at all. Anyone know whats goin on? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Untitled Document</title> <script...
4
13909
by: Sin Jeong-hun | last post by:
Most applications, including Windows Explorer, show some sort of 'wait' dialog with animation when a lengthy operation is going on. For example, When the Windows Explorer is searching for something, it shows a small dialog with a moving flashlight. I examined the explorer.exe and found that that was an avi file. Now that, I would like to do similar thing in my C# application. But what is the most efficient way to do so? 1)Manually...
0
8283
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8811
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8590
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7302
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6160
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5620
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4147
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4291
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1591
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.