Help Needed: Automator Applescript for Folder Action - Encode Video

Hi !
I have created an Automator Applescript for a Folder Action to do the following:
When a new video file is moved to the target folder (i.e. Download of Vuze is done), automatically launch the Applescript Action that does the followin g(Applescripted):
1) Using "run shell script" and FFMPEG on a UNIX command line, determine Width/Height, Framerate, Bitrate
2) Calculate encoding parameters (slightly reduced bitrate, reduced Aspect etc.)
3) Using "run shell script" with ffmpeg on the command line and the calculated parameters to encode the video file
At the same time, the action is written to a log file so I know if a file is recognized, when encoding started etc.
It works fine if I save this Action as an .app, make an alias on the Desktop and drop video files on it.
It also works fine if I attach the script to a folder as a folder action and drag a video file in there.
However, when I attach the script as a folder action to the Vuze download folder, it encodes only some video files, i.e. if there was a download of 5 files, chances are good that it will not encode 1 or 2 files out of those 5.
If for example a second download finishes while the encoding for the first download is still going on, sometimes the second file starts encoding after the first encode finishes, sometimes it does not, the file does not make the log file at all, i.e. the folder action missed it or the automator action dropped it because it was still encoding. Still, sometimes it happens, sometimes not.
As I need a solution that is 100% accurate, I would like to ask if there are any ideas on how to do this better maybe? As I am not an Applescript Guru, I would need some help to know what works and what doesn't and what the syntax is.
My main idea right now:
Similar to how ffmpegX works with its "process" application, have a second script (as .app) that receives the files to be encoded from the automator action and puts them in a queue, then proceeds to encode this queue while the main automator action is free to receive the next file.
Writing this second app is quite straightforward (a modified version of my current script) but I have some questions I need help with:
1) How do I call another applescript from within an existing applescript that launches the new applescript in a new process?
2) How do I pass parameters to this new applescript?
3) In case of this "Queueing" Idea, once I called the external applescript the first time, how do I make sure when I call next time, that I don't open a second instance of this script but rather pass another queue item to the original instance to be processed?
Or in general: Is there a better way to achieve this automatic encoding solution that I have not thought about?
Alternatively:
Does anyone know how to call the "process" application that comes with the ffmpegX package with the correct parameters to use as a queueing / processing tool?
Thanks!
Joe
Message was edited by: Joe15000
Message was edited by: Joe15000

To do this, I created an Automator workflow with an Applescript snippet to change the 'media kind'.
Here is the 'Run Applescript' workflow step code:
on run {input, parameters}
          tell application "iTunes"
                    set video kind of (item 1 of input) to movie
          end tell
          return input
end run
Prior to this running, I have an 'Import Files into iTunes' workflow step.
You can switch out 'movie' with: 'TV show', 'music video', or anything in ITLibMediaItemMediaKind.
Good luck,
Glenn

Similar Messages

  • Help Needed Creating AppleScript for Dial Up Access and Updates

    Hello,
    Due to my location I can only access the internet via Dial Up. I would like to create a script that wakes up my Mini early in the AM, dials my ISP and checks to see if there are any Apple Updates. I'd like to do this at night so my family doesn't have to compete with updates when they are using the computer.
    I've done the Apple Scripting tutorials and have a feel how to do the basics. But I cannot find any information on how to access the USB Modem (US Robotics), get it to dial, access the "Check for Updates" page, download, install and then disconnect.
    Can anyone point me to a functional script that will do this or tell me where I can find the modem related scripting commands?
    Thanks

    1). Does your script both get and install updates if they exist ? If not what should be added to accomplish that?
    If you use man softwareupdate to look at the command line options for softwareupdate you'll find:
    -i | --install
    Each update specified by args is downloaded and unarchived,
    and also installed. The install flag requires root. args
    can be one of the following:
    item ... One or more update names.
    -a | --all All appropriate updates.
    -r | --req All required updates.
    So '-i' tells softwareupdate to install the updates, and '-a' tells it to install all available updates, as opposed to a specific update, or 'required' ones.
    2). Can you suggest an addition to the script that will disconnect the dial up modem and then shut down our Mac Mini?
    That's going to be harder because, as written, the script performs the softwareupdate in the background. It does that so that you don't run into timeout issues (by default AppleScript will timeout after a certain period, canceling the script in progress). Since it's not clear how long the updates will take to download and install it isn't possible to predict what the appropriate timeout should be.
    The easiest way to disconnect would be to just configure the dialup connection to disconnect after a certain period of idleness (System Preferences -> Network -> Modem -> Advanced -> PPP -> Options or some such). If that doesn't suffice let me know and I'll craft up a revised script.

  • Applescript for folder reading

    I need a applescript for the below script.
    var inputDirectory="D:\\IndFiles";
    var inddFiles=new Array();
    inddFiles=Folder(inputDirectory).getFiles();
    //Suppress all dialogs
    app.scriptPreferences.userInteractionLevel = UserInteractionLevels.neverInteract;
    for(var indCount=0; indCount < inddFiles.length; indCount++)
        if (String(inddFiles[indCount]).match(/\.indd$/i))
            var aDoc=app.open(File(inddFiles[indCount]), true);
            //Save and close
            aDoc.close(2036691744);
    Arivu.

    With AppleScript you can use either POSIX or HFS paths. You just need to specify which you are passing. Shell will use POSIX, AppleScript by default likes HFS if you are going to coerce to an alias specifier (which is what most apps expect when using AppleScript). Here is another example that uses spotlight to find your files.
    set theFolder to quoted form of POSIX path of (choose folder)
    set fileList to paragraphs of (do shell script "mdfind -onlyin " & theFolder & " kMDItemDisplayName == '*.indd'")
    tell application "Adobe InDesign CS2"
    set user interaction level of script preferences to never interact
    repeat with i from 1 to count of fileList
    open (POSIX file (item i of fileList) as alias)
    -- do stuff
    close document 1 saving yes
    end repeat
    end tell
    I like 'mdfind' for its full POSIX paths and speed but it is recursive…
    If you have problems with 'your code' then you would do better to post it. And also what OS version  you are using?

  • Help with Simple Applescript for Midipipe

    Hey all, I'm in desperate need of help with some Applescript for use in a program called Midipipe:
    http://web.mac.com/nicowald/SubtleSoft/MidiPipe.html
    I simply require an Applescript for Midipipe that filters out all OFF notes except for the most recently pressed key, or most recently pressed ON note. So for example, when multiple keys have been pressed, only the most recently pressed key will send an OFF note. I hope that is clear enough, i've had some major issues trying to get this work and my last hope is to hit the forums and find some help .. I've posted on some of the audio forums and i'm hoping someone here knows how to code this.
    Thanks so much!! .. Its for an upcomming show next week so i'm hoping someone can get me in the right direction to solving this.
    -Jes

    I try to help, but you'll need to apply your brain cells to get it working with what I've already explained (three times with what I offer below).  Try something like the following (I am renaming your buttons to ch1,ch2,ch3,ch4,ch5,ch6 so that the same functions can be shared by all buttons...
    // this assigns listeners to all 6 buttons
    for(var i:uint=1; i<7; i++){
              this["ch"+String(i)].addEventListener(MouseEvent.CLICK, fl_ClickToSeekToCuePoint);
    // this processes any one of the 6 btns when they are clicked
    function fl_ClickToSeekToCuePoint_1(event:MouseEvent):void
        var btn = event.currentTarget;
        var cuePointInstance:Object = vid.findCuePoint(btn.name);
        vid.seek(cuePointInstance.time);
       resetButtons();    // this makes all buttons go back to normal
        btn.upState = btn.overState; // this makes the clicked button change states
    function resetButtons():void {
         for(var i:uint=1; i<7; i++){
              this["ch"+String(i)].upState =  this["ch"+String(i)].hitTestState;
    For this to work, your buttons need to have the same artwork in the hit frame as they do in the up frame.

  • Need an Applescript for...

    I need an Applescript for turning off my computer after it has been idle for 2hrs. Please and Thank you

    See this post. http://macscripter.net/viewtopic.php?pid=68885

  • Automator/Applescript for Pages

    Does anyone know of a good reference for Automator Actions or Applescripts for Pages? I've looked at all the usual websites and no one has any. All I'm trying to do is use a script to automate the process of opening Word docs and save them as Pages files.

    I do not think there is anything really well written and exhaustive on the matter. I have three main sources:
    1. Pages script dictionary (available in ScriptEditor through Open Dictionary > Pages).
    2. This page with a script that goes the opposite way: http://pagesfaq.blogspot.com/2006/11/i-have-one-thousand-pages-documents-to.html
    3. Searching Google for the string "tell application Pages".

  • Learning Unix commands (and automator/applescript) for a dummy :-)

    Hi:
    I've been supporting macs for many years and have done mostly user end support with all the various GUI tools. I've never been a programmer, never had the mind for it, etc.
    However, I've now reached the point where I need to do some kind of scripting and I'm looking for some good learning/training tools. I was wondering if anyone might have suggestions about the best training / reference guides to go about doing this. Right now, it's as if I need to play a little Beethoven, haven't learned Chopsticks yet and I'm trying to find out how to play chopsticks while learning a little Beethoven at the same time. (how's that for a metaphor?)
    For example: For my first project, I have to set up a backup for some laptop users so that certain files will be backed up. The need is different for each user, so this is why setting up a script would be easiest. My goals in the setting up this project are:
    - Make the script run at logout (logout hook)
    - check to make sure the network volume I want to backup to is present; if not present, stop the script
    - Use either cp or rsync to copy the files/directories to the shared volume.
    I've tried to look around the internet for help, examples, etc, but I've been unable to put together exactly the commands I need to sue to accomplish my task.
    Any suggestions would be great.
    Thanks!

    If you already know something about unix commands, there is a scripting tutorial at http://www.tldp.org/LDP/abs/html/index.html
    If you need a tutorial on unix commands, http://osxfaq.com/Tutorials/LearningCenter/UnixTutorials/LoseTheMouse/index.ws had a pretty good tutorial, although at the moment, that link isn't loading for me now so I don't know if it is still up online or not.
    for creating logout hooks, http://www.bombich.com/mactips/loginhooks.html might help.
    Also, in Terminal, type man launchd.plist if you can think of a scenario where you could implement a "cron-like" solution. Then refer to Apple's own periodic daily/weekly/monthly launchd plists (com.apple.periodic-*ly.plist) at/System/Library/LaunchDaemons/. There are more triggers available than just day/date/time, such as "watchPaths" and "RunAtLoad." Home grown launchd plists ones should go in /Library/LaunchDaemons/ or Library/LaunchAgents, not /System/Library/LaunchDaemons/. Also man launchd (no ".plist").

  • Need some help with Automator/AppleScript

    Hi guys, I'm trying to crate an automated process that will refresh a page that I've left open in a Safari window, search for a piece of text and, if said piece is not found, send me an e-mail (or better yet - iMessage). Basically, I want it to keep refreshing a page until it's contents change and then notify me.
    To get to the page I want to monitor, however, you need to go through a login (including captcha), so making Safari go to a certain URL won't work - I need it to refresh a page I've left open for it. Oh, and the page triggers an "Are you sure you want to send a form again?" dialogue if refreshed - the script should be able to confirm that (so it can keep refrshing).
    Also, it would be great if it's possible to make it run in the background, so I can use the computer while it's running.
    Any help will be very appreciated

    Then this should get you started. It grabs the URL of the current window and then repeatedly reloads it, looking for the specified keyword. You'll need to determine the actions to take when/if the keyword exists or doesn't.
    set keyword to "blah"
    tell application "Safari"
      -- get the current window
              set myWindow to (get current tab of window 1)
              repeat
                        do JavaScript "window.location.reload()" in myWindow
      -- wait for the page to load
                        repeat until ((do JavaScript "document.readyState;" in myWindow) is equal to "complete")
                                  delay 0.5
                        end repeat
                        set pageContent to text of myWindow
                        if pageContent contains keyword then
      -- code here for 'situation normal'
                        else
      -- code here for when text is missing
                        end if
      delay 2 -- wait a bit before running again
              end repeat
    end tell
    Since it stores a reference to the window you're free to do other things (open new windows, switch apps, etc.) as long as you don't close this window.

  • Need help converting old Applescript for Snow Leopard

    Ok, so I've downloaded the app "PowerHour" for mac. It needs to use the date function which is different in Snow Leopard, so I've heard. I don't program in Apple Script so I can't figure out what syntax to use. Can anyone help me fix this code below?
    I'm trying to code this because I don't think the original developer has any hand in this program anymore.
    The app on macupdate: http://www.macupdate.com/app/mac/24107/power-hour
    Here's the part that is giving the errors:
    set gameLengthAsDate to (date (zeroTime)) + (enteredMinutes * minutes)
    set songLengthAsDate to date (songLength)
    set gameStart to current date
    set songStart to gameStart
    set gameEnd to gameStart + (time of gameLengthAsDate)
    set songEnd to songStart + (time of songLengthAsDate)

    AppleScript in Snow Leopard is a bit pickier about specifying dates. From the AppleScript Release Notes, "the [date] string must exactly match one of the system date formats".
    It looks like the script is using a shortcut to set the time of the current date. I didn't test a modified application (just that the script statements set a valid date), but you might give the following a try:
    1) change the following properties (declared at the beginning of the script)property zeroTime : 0
    property songLength : 60
    2) change the statements that set the time toset gameLengthAsDate to (current date)
    set time of gameLengthAsDate to zeroTime + (enteredMinutes * minutes)
    set songLengthAsDate to (current date)
    set time of songLengthAsDate to songLength

  • A little help needed with AppleScript

    Hi:
    I need a little help with AppleScript.
    I created an AppleScript application to copy some files to a LAN disk that I always have mounted. The application works fine, except that it creates some sort of a lock that prevents me from doing other work with the Finder until the copy process is completed.
    If anyone has any ideas for how I can disable this lock, please let me know. I have included the source code of my script below.
    Thanks,
    -AstraPoint
    ===== source code =====
    with timeout of 1500 seconds
    tell application "Finder"
    activate
    set current_date to (do shell script "date '+%Y-%m-%d at %H-%M-%S'") as string
    set name_p to "Personal Data " & current_date & ".dmg"
    set name_d to "Documents " & current_date & ".dmg"
    (* copy the target files to another local disk - to create an extra backup *)
    duplicate file "Personal Data.dmg" of folder "File Backups" of disk "Macintosh HD" to folder "Ad Hoc Backups" of disk "Macintosh HDx" replacing yes
    set the name of file "Personal Data.dmg" of folder "Ad Hoc Backups" of disk "Macintosh HDx" to name_p
    duplicate file "Documents.dmg" of folder "File Backups" of disk "Macintosh HD" to folder "Ad Hoc Backups" of disk "Macintosh HDx" replacing yes
    set the name of file "Documents.dmg" of folder "Ad Hoc Backups" of disk "Macintosh HDx" to name_d
    (* mount remote disk/folder using the alias file on our desktop *)
    open alias file "disk HD5"
    (* copy the target files to a remote disk - to create an extra backup *)
    duplicate file name_p of folder "Ad Hoc Backups" of disk "Macintosh HDx" to folder "Bkup" of disk "HD5" replacing yes
    duplicate file name_d of folder "Ad Hoc Backups" of disk "Macintosh HDx" to folder "Bkup" of disk "HD5" replacing yes
    end tell
    end timeout

    Try:
    ignoring application responses
    Documented [here|http://developer.apple.com/library/mac/#documentation/AppleScript/Concept ual/AppleScriptLangGuide/reference/ASLRcontrolstatements.html].
    Message was edited by: xnav

  • Help needed with X11 for Gimp.

    Hi,
    I'm trying to install the open source imaging editing software GIMP (I'm to cheap to pay for photoshop!), and have tried to install X11 as required before installing GIMP but its not working.
    I've tried installing X11 by both downloading it from the Apple site and off the OS X install disk but when I download and try to run GIMP it's telling me I need to install X11 (even though it should be there already).
    After I've installed X11 I've checked to see if it's in the applications utilities folder but I can't see it.
    Can anyone point me in the right direction.
    Thanks,
    Joey.

    I Need help getting MacGimp to run.
    I just purchased MacGimp which is supposedly "The first shrink wrapped GiMP version for OS X". Downloaded, installed but when I launch it, the application starts briefly (icon bobbles in my dock) but then the application quits.
    I am getting NO response from MacGimp or GIMP people even though they have a support request form.
    So I am hoping people here can assist me. I am not proficient to download and compile code. Hence my delight to learn about MacGimp and I was willing to pay for it.
    But it does not run.... I wonder if something is missing?
    Because the MacGimp was supposed to complete and compiled, I have not installed X11 or anyting else.
    Do you think that is the problem.
    Will appreciate assistance. Really want to use GiMP as I don't want to pay hundreds of $ for Photoshop.
    Flat panel 15 iMac and MacBook 2 Gig Intel processor   Mac OS X (10.4.7)   MacBook has 2 Gig RAM, iMac has 1 Gig RAM
    Flat panel 15 iMac and MacBook 2 Gig Intel processor   Mac OS X (10.4.7)   MacBook has 2 Gig RAM, iMac has 1 Gig RAM

  • Help needed from Adobe for unauthorised activity on my account

    Help please!
    I bought some education software from an Adobe supplier on the recommendation of my school. It turns out (without me knowing or being told when I placed the order) that I was being sold old software, at what he now claims was cost price (interesting as I subsequently bought the next version for just $30 more). I have not been able to register that software as it was the wrong version for my region, and after a month of trying I asked for a refund.
    He is now accessing my account, (probably from a link in an email i sent him!!) and is trying to get the software he sold me registered so he doesn't have to refund me!
    Okay, so bad enough that I have hassles with this "person" but worse that he has access to my account and I seem unable to change this.
    This whole process has been a nightmare!! I need to close two open cases immediately but can't get hold of Adobe by phone or on chat!!! Help please!

    You should be able to contact chat support from http://adobe.ly/yxj0t6

  • Help needed in BAPI for uploading data in FB01 -  Urgent!!!

    Hi,
        i need to post a document in FB01.
    i am getting the following details from the user in a .CSV file.
    Vendor no, vendor name, amount, document date, posting datem reference vendor line item text and Gl account line item text.
    i am using BAPI BAPI_ACC_DOCUMENT_POST to post the document.
    Now my req is if the amount is in negative then
       use posting key 31 against the vendor and 40 for GL account
    if its positive amounts
      use posting key of 24 against vendor and 50 against the GL account.
    Now by default, when the amount is negative the function is working fine.
                    but when its is positive its posting 21 against vendor and 50 against GL account. but i need 24 against vendor
    can any one tel me, where should i pass these value in the BAPI?
    or is there any other way of doing it?
    Regards,
    Niyaz

    Hi,
    the posting keys 31/21 (01/11 and 40/50) are hard coded and cannot be populated from the  interface. This is because a different posting key could have a different posting logic from what is implemented in the BAPI.
    So unless you want to do some modifications here, you have to use the fixed PKs. Pls. let me know if you are interested in where exactly the PKs are defined (hardcoded). I have this noticed for myself earlier but my notices are on another PC
    Hope that helps, points welcome
    Csaba

  • Help needed with DisplayConfigX for Philips 32PW9551/12 CRT TV

    Hi everyone,
    I've been following this part of Apple Discussions closely for some time now, and I realise that I'm not the only one having trouble connecting my Mac Mini (Core Duo) to my TV. I'm hoping that BSteely or somebody else here could take a look at my specific problem. I'll try to provide as much relevant info as I can, if more input is needed, please specify.
    Here goes :
    TV model : Philips 32PW9551/12 That's a CRT, but with HDMI input. The manual says that it should accept 480p, 576p, 720p and 1080i.
    Cable : DVI-HDMI
    Using VNC over Airport when things go wrong, resetting back to the original resolutions.
    Problem : can't get 720p resolution to work, only 640x480 fills screen. 640x480 is too low, since Remote Buddy's menu does not even fit on it.
    When I select 1280x720 the image is on the left of the TV, leaving a wide black bar on the right and dropping a lot on the right. Other resolutions either don't work at all, are seriously overscanned (no dock, no menu) or are horrible to look at.
    I've been fiddling with DisplayConfigX and SwitchResX, but I feel it's out of my league, so I'm not getting anywhere. I did export settings via SwitchResX, I hope that provides some insights.
    Thank you very much in advance for helping me get my setup to work by creating a tailormade timing !
    Kind regards,
    Also Starring
    Belgium
    DDC block report generated by SwitchResX for display
    PhilipsTV
    0 1 2 3 4 5 6 7 8 9 A B C D E F
    0 | 00 FF FF FF FF FF FF 00 41 0C 51 95 01 01 01 01
    1 | 06 10 01 03 80 42 25 78 0A 0D C9 A0 57 47 98 27
    2 | 12 48 4C 20 00 00 01 01 01 01 01 01 01 01 01 01
    3 | 01 01 01 01 01 01 01 1D 80 D0 72 1C 16 20 10 2C
    4 | 25 80 94 72 21 00 00 9E 01 1D 00 72 51 D0 1E 20
    5 | 6E 28 55 00 94 72 21 00 00 1E 00 00 00 FD 00 31
    6 | 3D 1C 2E 08 00 0A 20 20 20 20 20 20 00 00 00 FC
    7 | 00 4C 30 36 48 44 20 76 31 20 31 36 3A 39 01 29
    Valid DDC block: checksum passed
    EDID Version........1.3
    Manufacturer........PHL
    Product Code........20885 (5195) (9551)
    Serial Number.......16843009
    Manufactured........Week 6 of year 2006
    Max H Size..........66 cm
    Max V Size..........37 cm
    Gamma...............2.20
    DPMS Supported Features:
    Display type:
    RGB color display
    Input signal & sync:
    Digital
    Color info:
    Red x = 0.625 Green x = 0.280 Blue x = 0.155 White x = 0.283
    Red y = 0.340 Green y = 0.595 Blue y = 0.070 White y = 0.298
    Established Timings:
    640 x 480 @ 60Hz
    Manufacturer Reserved Timings:
    Standard Timing Identification:
    Monitor Description blocks:
    Descriptor #0 is Timing definition:
    Mode = 1920 x 540 @ 50Hz
    H. Active...............1920 pixels
    H. Blanking.............720 pixels
    V. Active...............540 lines
    V. Blanking.............22 lines
    HSync Offset............528 pixels
    HSync Pulse Width.......44 pixels
    VSync Offset............2 lines
    VSync Pulse Width.......5 lines
    Pixel Clock.............74.25MHz
    Horizontal freq.........28.12kHz
    Vertical freq...........50.04Hz
    H Image Size............660mm
    V Image Size............370mm
    H Border................0 pixels
    V Border................0 lines
    Interlaced
    Sync: Digital separate with
    * Positive vertical polarity
    * Positive horizontal polarity
    Descriptor #1 is Timing definition:
    Mode = 1280 x 720 @ 60Hz
    H. Active...............1280 pixels
    H. Blanking.............370 pixels
    V. Active...............720 lines
    V. Blanking.............30 lines
    HSync Offset............110 pixels
    HSync Pulse Width.......40 pixels
    VSync Offset............5 lines
    VSync Pulse Width.......5 lines
    Pixel Clock.............74.25MHz
    Horizontal freq.........45.00kHz
    Vertical freq...........60.00Hz
    H Image Size............660mm
    V Image Size............370mm
    H Border................0 pixels
    V Border................0 lines
    Non-Interlaced
    Sync: Digital separate with
    * Positive vertical polarity
    * Positive horizontal polarity
    Descriptor #2 is Monitor limits:
    Horizontal frequency range.......28-46 kHz
    Vertical frequency range.........49-61 Hz
    Maximum bandwidth unspecified
    Descriptor #3 is Monitor name:
    L06HD v1 16:9
    Mini Intel Core Duo   Mac OS X (10.4.8)  

    (1280x594 60Hz NTSC) gives fairly stable
    image, big black border on
    top, fallen off image on the left but right and
    bottom seem ok.
    You might want to run with that and see if you can dial it in better. SwitchRes X has arrows you can use in the right-hand side of the custom pane where you can try and center and size the image better.
    Another thing. I don't seem to be able to enter the
    pixel clock number exactly as you specify. It keeps
    changing it slightly. Eg, after rebooting, it says
    68,4 in SRX, even though I entered 69,75 before...
    This is explained in the SRX documentation. When you make a request of the hardware that it somehow can't satisfy, it just tries to do the next closest thing. But you don't get and feedback of what the hardware can and cannot do. You only get unexpected results as you have mentioned.
    And also, should the vertical scan rate not be
    exactly 60 Hz ? Other numbers don't seem to be
    accepted by the TV, but when making custom timings,
    these scan rate numbers seem to be changing all the
    time.
    If you look at the EDID data you posted at the begining of this thread, towards the bottom it states that your TV will work from with any vertical frequency in the range of 49Hz to 61Hz. You don't need to use 60Hz but that is a standard. There is very little downside to deviating from that with and LCD display.

  • Help Needed with Itemlsteners for Choice in AWT

    Hi,
    I am new to AWT prgramming .
    I have created a menu called " Menu System Test window " and it contains toplevel menu item "File" and File Menu contains subitems "Product Evaluation" and "Exit".
    When i click File->Product Evaluation it displays a new Frame named "ProductEvaluationMeasurementTool" with some check boxes ,radiobuttons, buttons , text fields and choice lists.
    The two Choices ie c1 and c2 contains items choice,choice2 and scale 1 and scale 2 respectively and i have added ItemListeners for both the choices.
    My question is when i select Both choice1 and scale 1 it shoulddisplay a new frame.
    (NOTE : THE NEW FRAME SHOULD BE DISPLAYED IF I SELECT BOTH CHOICE1 AND SCALE1 NOT EITHER CHOICE1 OR SCALE1)
    Similarly when i select Both choice2 and scale2 it should display another new frame. How can i do that? i am sending my code.
    Thanks in advance
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Component;
    import java.awt.Checkbox;
    import javax.swing.*;
    // Make a main window with a top-level menu: File 
    public class MainWindow extends Frame {
      public MainWindow() {
        super("Menu System Test Window");
        setSize(500, 500);
        // make a top level File menu
        FileMenu fileMenu = new FileMenu(this);
        // make a menu bar for this frame 
        // and add top level menus File and Menu
        MenuBar mb = new MenuBar();
        mb.add(fileMenu);
        setMenuBar(mb);
        addWindowListener(new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            exit();
      public void exit() {
        setVisible(false); // hide the Frame
        dispose(); // tell windowing system to free resources
        System.exit(0); // exit
      public static void main(String args[]) {
        MainWindow w = new MainWindow();
        w.setVisible(true);
    // Encapsulate the look and behavior of the File menu
    class FileMenu extends Menu implements ActionListener {
        private MainWindow mw; // who owns us?
      private MenuItem itmPE   = new MenuItem("ProductEvaluation");
      private MenuItem itmExit = new MenuItem("Exit");
      public FileMenu(MainWindow main)
        super("File");
        this.mw = main;
        this.itmPE.addActionListener(this);
        this.itmExit.addActionListener(this);
        this.add(this.itmPE);
        this.add(this.itmExit);
      // respond to the Exit menu choice
      public void actionPerformed(ActionEvent e)
        if (e.getSource() == this.itmPE)
         Frame f = new Frame("ProductMeasurementEvaluationTool");
         f.setSize(1290,1290);
         f.setLayout(null);
         TextField t1 = new TextField("textField1");
         t1.setBounds(230, 630, 50, 24);
         f.add(t1);
         TextField t2 = new TextField("textField2");
         t2.setBounds(430, 630, 50, 24);
         f.add(t2);
         Choice c1 = new Choice();
         c1.addItem("Choice1");
         c1.addItem("Choice2");
         c1.addItemListener(new MyItemListener());
         f.add(c1);
         c1.setBounds(630, 600, 120, 24);
         Choice c2 = new Choice();
         c2.addItem("scale1");
         c2.addItem("scale2");
         c2.addItemListener(new MyItemListener());
         f.add(c2);
         c2.setBounds(840, 600, 120, 24);
         Label l1 = new Label("Select the appropriate metrics for Measurement Process Evaluation");
         l1.setBounds(380, 50, 380, 20);
         f.add(l1);
         Label l2 = new Label("Architecture Metrics");
         l2.setBounds(170, 100, 110, 20);
         f.add(l2);
         Label l3 = new Label("RunTime Metrics");
         l3.setBounds(500, 100, 110, 20);
         f.add(l3);
         Label l4 = new Label("Documentation Metrics");
         l4.setBounds(840, 100, 130, 20);
         f.add(l4);
         JRadioButton rb1 = new JRadioButton("Componenent Metrics",false);
         rb1.setBounds(190, 140, 133, 20);
         f.add(rb1);
         JRadioButton rb2 = new JRadioButton("Task Metrics",false);
         rb2.setBounds(540, 140, 95, 20);
         f.add(rb2);
         JRadioButton rb3 = new JRadioButton("Manual Metrics",false);
         rb3.setBounds(870, 140, 108, 20);
         f.add(rb3);
         JRadioButton rb4 = new JRadioButton("Configuration Metrics",false);
         rb4.setBounds(190, 270, 142, 20);
         f.add(rb4);
         JRadioButton rb6 = new JRadioButton("DataHandling Metrics",false);
         rb6.setBounds(540, 270, 142, 20);
         f.add(rb6);
         JRadioButton rb8 = new JRadioButton("Development Metrics",false);
         rb8.setBounds(870, 270, 141, 20);
         f.add(rb8);
         Checkbox  c10 = new Checkbox("Size");
         c10.setBounds(220, 170, 49, 20);
         f.add(c10);
         Checkbox c11 = new Checkbox("Structure");
         c11.setBounds(220, 190, 75, 20);
         f.add(c11);
         Checkbox c12 = new Checkbox("Complexity");
         c12.setBounds(220, 210, 86, 20);
         f.add(c12);
         Checkbox c13 = new Checkbox("Size");
         c13.setBounds(220, 300, 49, 20);
         f.add(c13);
         Checkbox c14 = new Checkbox("Structure");
         c14.setBounds(220, 320, 75, 20);
         f.add(c14);
         Checkbox c15 = new Checkbox("Complexity");
         c15.setBounds(220, 340, 86, 20);
         f.add(c15);
         Checkbox c19 = new Checkbox("Size");
         c19.setBounds(580, 170, 49, 20);
         f.add(c19);
         Checkbox c20 = new Checkbox("Structure");
         c20.setBounds(580, 190, 75, 20);
         f.add(c20);
         Checkbox c21 = new Checkbox("Complexity");
         c21.setBounds(580, 210, 86, 20);
         f.add(c21);
         Checkbox c22 = new Checkbox("Size");
         c22.setBounds(580, 300, 49, 20);
         f.add(c22);
         Checkbox c23 = new Checkbox("Structure");
         c23.setBounds(580, 320, 75, 20);
         f.add(c23);
         Checkbox c24 = new Checkbox("Complexity");
         c24.setBounds(580, 340, 86, 20);
         f.add(c24);
         Checkbox c28 = new Checkbox("Size");
         c28.setBounds(920, 170, 49, 20);
         f.add(c28);
         Checkbox c29 = new Checkbox("Structure");
         c29.setBounds(920, 190, 75, 20);
         f.add(c29);
         Checkbox c30 = new Checkbox("Complexity");
         c30.setBounds(920, 210, 86, 20);
         f.add(c30);
         Checkbox c31 = new Checkbox("Size");
         c31.setBounds(920, 300, 49, 20);
         f.add(c31);
         Checkbox c32 = new Checkbox("Structure");
         c32.setBounds(920, 320, 75, 20);
         f.add(c32);
         Checkbox c33 = new Checkbox("Complexity");
         c33.setBounds(920, 340, 86, 20);
         f.add(c33);
         ActionListener action = new MyActionListener(f, t1, t2);
         Button b1  = new Button("Button1");
         b1.setBounds(230, 600, 120, 24);
         b1.addActionListener(action);
         f.add(b1);
         Button b2  = new Button("Button2");
         b2.setBounds(430, 600, 120, 24);
         b2.addActionListener(action);
         f.add(b2);
               f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e)
              System.exit(0);
         f.show();
        else
       { mw.exit();}
    class MyActionListener implements ActionListener
      private Frame     frame;
      private TextField textField1;
      private TextField textField2;
      public MyActionListener(Frame frame, TextField tf1, TextField tf2)
        this.frame = frame;
        this.textField1 = tf1;
        this.textField2 = tf2;
      public void actionPerformed(ActionEvent e)
        String s = e.getActionCommand();
        if (s.equals("Button1"))
            Component[] components = this.frame.getComponents();
      int numOfCheckBoxes = 81;
      int numChecked = 0;
      for (int i = 0; i < components.length; i++)
            if (components[i] instanceof Checkbox)
              if (((Checkbox)components).getState())
    numChecked++;
    double ratio = (double) numChecked / (double) numOfCheckBoxes;
    this.textField1.setText(Double.toString(ratio));
    else
    if (s.equals("Button2"))
    Component[] components = this.frame.getComponents();
    int numOfCheckBoxes = 81;
    int numChecked = 0;
    for (int i = 0; i < components.length; i++)
    if (components[i] instanceof Checkbox)
    if (((Checkbox)components[i]).getState())
    numChecked++;
    double ratio = (double) numChecked / (double) numOfCheckBoxes;
    this.textField2.setText(Double.toString(ratio));
    class MyItemListener implements ItemListener {
         public void itemStateChanged(ItemEvent e) {
                   String command = (String) e.getItem();

    The easy answer is that you need to add state to one of your classes. What does this mean? Somewhere you will have to keep track of which items are selected in each Choice. There are a lot of ways to do this. One way is to pass a reference for each Choice, ie, c1 and c2, in to the constructor of MyItemListener and for each ItemEvent.SELECTED type of event:
    1 - check the selected item of each Choice and see if they have the same ending number, or are the same index in an array kept in your MyItemListener class or ... many ways;
    2 - decide what to do depending on what you find after checking.
    Since you have a separate class for the ItemListener this might be a good place to keep track of the selection status of the two Choice components. The member variables you use to keep track of things is the state.
    Another thing to consider is whether to add a separate listener to each Choice or to create a single instance and add it to each component. If you add a separate one then the Choice selections won't know about each other - each separate listener receives events from only one of the components. If you use a single instance for both components then you can get selection information from each of the Choice components. This way you can track things, or keep state, inside the class.
    I abbreviated the class name so you can run this without name-clashing in your computer.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Component;
    import java.awt.Checkbox;
    import javax.swing.*;
    public class MW extends Frame {
        public MW() {
            super("Menu System Test Window");
            setSize(500, 500);
            // make a top level File menu
            FileMenu fileMenu = new FileMenu(this);
            // make a menu bar for this frame 
            // and add top level menus File and Menu
            MenuBar mb = new MenuBar();
            mb.add(fileMenu);
            setMenuBar(mb);
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    exit();
        public void exit() {
            setVisible(false); // hide the Frame
            dispose();         // tell windowing system to free resources
            System.exit(0);    // exit
        public static void main(String args[]) {
            MW w = new MW();
            w.setVisible(true);
    // Encapsulate the look and behavior of the File menu
    class FileMenu extends Menu implements ActionListener {
        private MW mw; // who owns us?
        private MenuItem itmPE   = new MenuItem("ProductEvaluation");
        private MenuItem itmExit = new MenuItem("Exit");
        public FileMenu(MW main) {
            super("File");
            this.mw = main;
            this.itmPE.addActionListener(this);
            this.itmExit.addActionListener(this);
            this.add(this.itmPE);
            this.add(this.itmExit);
        // respond to the Exit menu choice
        public void actionPerformed(ActionEvent e) {
            if (e.getSource() == this.itmPE) {
                final Frame f = new Frame("ProductMeasurementEvaluationTool");
                f.setSize(1290,1290);
                f.setLayout(null);
                MyItemListener itemListener = new MyItemListener(mw);
                TextField t1 = new TextField("textField1");
                t1.setBounds(230, 630, 50, 24);
                f.add(t1);
                TextField t2 = new TextField("textField2");
                t2.setBounds(430, 630, 50, 24);
                f.add(t2);
                Choice c1 = new Choice();
                c1.addItem("Choice1");
                c1.addItem("Choice2");
                c1.addItemListener(itemListener);
                f.add(c1);
                c1.setBounds(630, 600, 120, 24);
                Choice c2 = new Choice();
                c2.addItem("scale1");
                c2.addItem("scale2");
                c2.addItemListener(itemListener);
                f.add(c2);
                c2.setBounds(840, 600, 120, 24);
                Label l1 = new Label("Select the appropriate metrics for " +
                                     "Measurement Process Evaluation");
                l1.setBounds(380, 50, 380, 20);
                f.add(l1);
                Label l2 = new Label("Architecture Metrics");
                l2.setBounds(170, 100, 110, 20);
                f.add(l2);
                Label l3 = new Label("RunTime Metrics");
                l3.setBounds(500, 100, 110, 20);
                f.add(l3);
                Label l4 = new Label("Documentation Metrics");
                l4.setBounds(840, 100, 130, 20);
                f.add(l4);
                JRadioButton rb1 = new JRadioButton("Componenent Metrics",false);
                rb1.setBounds(190, 140, 133, 20);
                f.add(rb1);
                JRadioButton rb2 = new JRadioButton("Task Metrics",false);
                rb2.setBounds(540, 140, 95, 20);
                f.add(rb2);
                JRadioButton rb3 = new JRadioButton("Manual Metrics",false);
                rb3.setBounds(870, 140, 108, 20);
                f.add(rb3);
                JRadioButton rb4 = new JRadioButton("Configuration Metrics",false);
                rb4.setBounds(190, 270, 142, 20);
                f.add(rb4);
                JRadioButton rb6 = new JRadioButton("DataHandling Metrics",false);
                rb6.setBounds(540, 270, 142, 20);
                f.add(rb6);
                JRadioButton rb8 = new JRadioButton("Development Metrics",false);
                rb8.setBounds(870, 270, 141, 20);
                f.add(rb8);
                Checkbox  c10 = new Checkbox("Size");
                c10.setBounds(220, 170, 49, 20);
                f.add(c10);
                Checkbox c11 = new Checkbox("Structure");
                c11.setBounds(220, 190, 75, 20);
                f.add(c11);
                Checkbox c12 = new Checkbox("Complexity");
                c12.setBounds(220, 210, 86, 20);
                f.add(c12);
                Checkbox c13 = new Checkbox("Size");
                c13.setBounds(220, 300, 49, 20);
                f.add(c13);
                Checkbox c14 = new Checkbox("Structure");
                c14.setBounds(220, 320, 75, 20);
                f.add(c14);
                Checkbox c15 = new Checkbox("Complexity");
                c15.setBounds(220, 340, 86, 20);
                f.add(c15);
                Checkbox c19 = new Checkbox("Size");
                c19.setBounds(580, 170, 49, 20);
                f.add(c19);
                Checkbox c20 = new Checkbox("Structure");
                c20.setBounds(580, 190, 75, 20);
                f.add(c20);
                Checkbox c21 = new Checkbox("Complexity");
                c21.setBounds(580, 210, 86, 20);
                f.add(c21);
                Checkbox c22 = new Checkbox("Size");
                c22.setBounds(580, 300, 49, 20);
                f.add(c22);
                Checkbox c23 = new Checkbox("Structure");
                c23.setBounds(580, 320, 75, 20);
                f.add(c23);
                Checkbox c24 = new Checkbox("Complexity");
                c24.setBounds(580, 340, 86, 20);
                f.add(c24);
                Checkbox c28 = new Checkbox("Size");
                c28.setBounds(920, 170, 49, 20);
                f.add(c28);
                Checkbox c29 = new Checkbox("Structure");
                c29.setBounds(920, 190, 75, 20);
                f.add(c29);
                Checkbox c30 = new Checkbox("Complexity");
                c30.setBounds(920, 210, 86, 20);
                f.add(c30);
                Checkbox c31 = new Checkbox("Size");
                c31.setBounds(920, 300, 49, 20);
                f.add(c31);
                Checkbox c32 = new Checkbox("Structure");
                c32.setBounds(920, 320, 75, 20);
                f.add(c32);
                Checkbox c33 = new Checkbox("Complexity");
                c33.setBounds(920, 340, 86, 20);
                f.add(c33);
                ActionListener action = new MyActionListener(f, t1, t2);
                Button b1  = new Button("Button1");
                b1.setBounds(230, 600, 120, 24);
                b1.addActionListener(action);
                f.add(b1);
                Button b2  = new Button("Button2");
                b2.setBounds(430, 600, 120, 24);
                b2.addActionListener(action);
                f.add(b2);
                f.addWindowListener(new WindowAdapter() {
                    public void windowClosing(WindowEvent e) {
                        //System.exit(0);
                        f.dispose();
                f.setVisible(true);
            else {
                mw.exit();
    class MyActionListener implements ActionListener { 
        private Frame     frame;
        private TextField textField1;
        private TextField textField2;
        public MyActionListener(Frame frame, TextField tf1, TextField tf2) {
            this.frame = frame;
            this.textField1 = tf1;
            this.textField2 = tf2;
        public void actionPerformed(ActionEvent e) {
            String s = e.getActionCommand();
            if (s.equals("Button1")) {
                Component[] components = this.frame.getComponents();
                int numOfCheckBoxes = 81;
                int numChecked = 0;
                for (int i = 0; i < components.length; i++)
                    if (components[i] instanceof Checkbox)
                        if (((Checkbox)components).getState())
    numChecked++;
    double ratio = (double) numChecked / (double) numOfCheckBoxes;
    this.textField1.setText(Double.toString(ratio));
    else if (s.equals("Button2")) {
    Component[] components = this.frame.getComponents();
    int numOfCheckBoxes = 81;
    int numChecked = 0;
    for (int i = 0; i < components.length; i++)
    if (components[i] instanceof Checkbox)
    if (((Checkbox)components[i]).getState())
    numChecked++;
    double ratio = (double) numChecked / (double) numOfCheckBoxes;
    this.textField2.setText(Double.toString(ratio));
    class MyItemListener implements ItemListener {
    Frame owner;
    Dialog dialog;
    Label label;
    boolean haveScale1, haveScale2, haveChoice1, haveChoice2;
    public MyItemListener(MW mw) {
    owner = (Frame)mw;
    initializeDialog();
    haveScale1 = true;
    haveScale2 = false;
    haveChoice1 = true;
    haveChoice2 = false;
    public void itemStateChanged(ItemEvent e) {
    if(e.getStateChange() == ItemEvent.SELECTED) {
    String command = (String) e.getItem();
    System.out.println("command = " + command);
    if(command.equals("scale1")) {
    haveScale1 = true;
    haveScale2 = false;
    if(command.equals("scale2")) {
    haveScale2 = true;
    haveScale1 = false;
    if(command.equals("Choice1")) {
    haveChoice1 = true;
    haveChoice2 = false;
    if(command.equals("Choice2")) {
    haveChoice2 = true;
    haveChoice1 = false;
    if(haveScale1 && haveChoice1)
    launchDialog(1);
    if(haveScale2 && haveChoice2)
    launchDialog(2);
    private void launchDialog(int n) {
    label.setText("scale" + n + " and Choice" + n + " chosen");
    dialog.setVisible(true);
    private void initializeDialog() {
    label = new Label();
    label.setAlignment(Label.CENTER);
    dialog = new Dialog(owner, "item listener dialog", false);
    dialog.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent e) {
    dialog.dispose();
    dialog.add(label); // to center of default BorderLayout
    dialog.setSize(200,100);
    dialog.setLocation(300,300);

Maybe you are looking for