A very quick introduction to Java...

Apr 16, '03 09:29:00AM

Contributed by: patrickoehlinger

Mac OS X has a great Java environment. Wanna get started? Write a quick app to control iTunes (or any other AppleScriptable App). The following Java file will help you control iTunes:


import com.apple.cocoa.foundation.*;

public class iTunesControl {

  public void play() {    doScript("tell application \"itunes\" to play"); }
  public void pause() {   doScript("tell application \"itunes\" to pause"); }
  public void next() {    doScript("tell application \"itunes\" to next track"); }
  public void previous() {doScript("tell application \"itunes\" to previous track"); }
  
  private void doScript(String script) {
        
    // This creates a new NSAppleScript
    // object to execute the script
    NSAppleScript myScript = new NSAppleScript(script);

    // This dictionary holds any errors that are
    // encountered during script execution
    NSMutableDictionary errors = new NSMutableDictionary(); 

    // Execute the script!
    myScript.execute(errors); 
  }
}
To use the com.apple.cocoa.foundation.* lib provided with every version of OS X, type:
setenv CLASSPATH /System/Library/Java/:

Read the rest of the article for instructions on how to use the above class...

An easy way to play around with the iTunesControl class would be:


public class music {
  public static void main(String[] args) { 
    iTunesControl cont = new iTunesControl();

    if(args[0].equals("play"))      cont.play();
    if(args[0].equals("pause"))     cont.pause();
    if(args[0].equals("next"))      cont.next();    
    if(args[0].equals("previous")) cont.previous();
  }
}
To get started, try the following steps:
  1. Save the first file as iTunesControl.java
  2. Save the second file as music.java
  3. Start the Terminal an d change in the directory where you stored the above files
  4. To set the correct classpath, type in the Terminal: setenv CLASSPATH "/System/Library/Java/:"
  5. Now compile the Java files with: javac *.java
  6. Start iTunes with: java music play
  7. Next Song with: java music next
  8. Same for: pause and previous
Hopefully this helps you get started with Java and AppleScript; if you want to learn more about Java, follow this tutorial. Next step would be to include this java file in a .jsp file so we can control iTunes from (any) Web Browser in the world. To do so, you need Tomcat. But thanks to this step by step guide, that's easy.

Comments (8)


Mac OS X Hints
http://hints.macworld.com/article.php?story=2003041418033512