Sound in a jFrame

Hi, just want to ask if anyone has any code samples to play files using a jFrame (not an applet) using the javax.sound.sampled package. All I am trying to do is play a sound file that is already defined in the code when I press a button. All I can find are complex programs and 2 page long explanation documents.
Any help would be kindly appreciated.

Does it have to be that special package, or would
anything that works help like using AudioClip?
    String clipname = "sound.wav";
try {
URL clipUrl = new URL("file:" + clipname);
AudioClip audioClip =
Applet.newAudioClip(clipUrl);
audioClip.play();
Thread.currentThread().sleep(3000);
} catch (Exception e) {
e.printStackTrace();
hey, String clipname = "sound.wav"; goes in the atributes declaration? or it goes later than the constructor of the class? where it goes?, sorry for questionate a lot, Im trying to learning

Similar Messages

  • Add sound to JFrame

    I have a button in my JFrame and want to assign sound to it.
    ActionListener code is already written, only the sound part is left.
    Thanks for helping.(clear as you can get because im new in java)

    At the beginning fo your action listener, try:
    AudioClip audioClip = Applet.newAudioClip("C:\\temp\\sound1.wav");
    audioClip.play();     //Play it once.This page shows you how to play sound so it loads faster.
    http://java.sun.com/docs/books/tutorial/sound/playing.html

  • Help with playing sound in applications

    im new to java and i was practicing playing sound in a swing application but the problem is that when i press the play button no sound is played...here is my code
    import javax.swing.*;
    import java.applet.AudioClip;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.io.File;
    public class JukeBox extends JFrame {
        private JLabel label;
        private JPanel panel, buttonPanel;
        private JComboBox playList;
        private JButton play, stop;
        private URL url1, url2, url3, url4, url5, url6;
        private AudioClip[] musicList;
        private AudioClip current ;
        public JukeBox() {
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setSize(500, 120);
            setLocation(50, 50);
            setTitle("JAVA JukeBox");
            url1 = url2 = url3 = url4 = url5 = url6 = null;
            current = null;
            try {
                url1 = new URL("file", "localhost", "C:\\Documents and Settings\\KADA\\IdeaProjects\\Sound\\bottle-open.wav");
                url2 = new URL("file", "localhost", "C:\\Documents and Settings\\KADA\\IdeaProjects\\Sound\\BP2.mp3");
                url3 = new URL("file", "localhost", "C:\\Documents and Settings\\KADA\\IdeaProjects\\Sound\\fhm.aiff");
                url4 = new URL("file", "localhost", "C:\\Documents and Settings\\KADA\\IdeaProjects\\Sound\\jungle.rmf");
                url5 = new URL("file", "localhost", "C:\\Documents and Settings\\KADA\\IdeaProjects\\Sound\\spacemusic.au");
                url6 = new URL("file", "localhost", "C:\\Documents and Settings\\KADA\\IdeaProjects\\Sound\\trippygaia.mid");
            } catch (MalformedURLException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            musicList = new AudioClip[7];
            musicList[0] = null;
            musicList[1] = JApplet.newAudioClip(url1);
            musicList[2] = JApplet.newAudioClip(url2);
            musicList[3] = JApplet.newAudioClip(url3);
            musicList[4] = JApplet.newAudioClip(url4);
            musicList[5] = JApplet.newAudioClip(url5);
            musicList[6] = JApplet.newAudioClip(url6);
            label = new JLabel("JAVA JukeBox", JLabel.CENTER);
            String[] musicList = {"select a track..."
                    , "bottle open"
                    , "bitch please II"
                    , "flutte, harmonica, mambo"
                    , "jungle"
                    , "spacemusic"
                    , "trippygaia"};
            playList = new JComboBox(musicList);
            playList.addActionListener(new ListListener());
            play = new JButton("Play");
            play.setActionCommand("play");
            play.addActionListener(new ButtonListener());
            stop = new JButton("Stop");
            stop.addActionListener(new ButtonListener());
            buttonPanel = new JPanel();
            buttonPanel.setLayout(new BoxLayout(buttonPanel, BoxLayout.X_AXIS));
            buttonPanel.add(play);
            buttonPanel.add(stop);
            panel = new JPanel();
            panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
            panel.add(label);
            panel.add(Box.createRigidArea(new Dimension(0, 5)));
            panel.add(playList);
            panel.add(Box.createRigidArea(new Dimension(0, 5)));
            panel.add(buttonPanel);
            getContentPane().add(panel);
        private class ButtonListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                if(current != null){
                    current.stop();
                if(e.getActionCommand().equalsIgnoreCase("play")){
                    if(current != null){
                        current.play();
        private class ListListener implements ActionListener {
            public void actionPerformed(ActionEvent e) {
                if (current != null) {
                    current.stop();
                current = musicList[playList.getSelectedIndex()];
        public static void main(String[] args) {
            setDefaultLookAndFeelDecorated(true);
            JukeBox jb = new JukeBox();
            jb.setVisible(true);
            jb.setResizable(false);
    }can u please tell me whats wrong with my code coz i cant hear no sound when i press the play button and can u please tell me why i cant simply put the file name in the URL instead of the complete path although the files are in the same directory of the source code and can i play mp3 using this little program ???
    plz help...im a newbie so plz explain as much as u can...

    After
    musicList = new AudioClip[7];
            musicList[0] = null;
            musicList[1] = JApplet.newAudioClip(url1);
            musicList[2] = JApplet.newAudioClip(url2);
            musicList[3] = JApplet.newAudioClip(url3);
            musicList[4] = JApplet.newAudioClip(url4);
            musicList[5] = JApplet.newAudioClip(url5);
            musicList[6] = JApplet.newAudioClip(url6);initialise the variable current with
    current = musicList[1];or similar because the AudioClip current always == null in your code so your listener blocks don`t execute.
    regards

  • I can't don't understand code in netbean and it's about Jframe.

    i use netbean to design 2 jframe with some buttons on both frame.
    frame1 is login form, frame2 is mainform. i want to show loginform then click the button1 to show 2nd jframe.
    then i click exit on 2nd jframe and it come back to loginform(frame1).
    i do alot of search on the google and here. i know the basic to show a jframe using
    setVisible or .show() .hide(), etc..
    the problem is what is my jframe variable name in netbean?
    i know i can create an jframe object
    such as: JFrame frame1 = new JFrame(); etc.. (it's ok if the syntax is wrong for now).
    When i use netbean, i drag the Gui components to the Jframe. The jframe is generated by netbean automatically.
    When the main program runs, it calls main() method, follow by :
    public void run() {
    new LoginForm().setVisible(true);
    new LoginForm().setVisible <--- setVisible(true) means show the form.
    and is new LoginForm() create an object from LoginForm class.
    public LoginForm() {
    initComponents();
    When it create a new object, it runs default constructor and calls iniComponoents and finally show the jframe.
    my question is when you create object, you usually declare variable and use variable to hold reference to the object.
    that's why i don't understand how it works here.
    it only create news object, bu no variable to holding it. how do i control this Jframe to show and hide without a reference variable????????????
    Edited by: roadorange on Feb 29, 2008 10:08 PM

    roadorange wrote:
    Encephalopathic . thank your reply so much. your reply is fast. i love it and love this forum.. LOLyou're welcome
    i tried hand-written code, and it looks just fine when design few buttons, labels and textfields.
    The adjustment of buttons(labels) are not that good on the frame.
    However, when you use IDE, you can drag the button on any spot you like in the jframe.... and in the process not learn how Swing works, and lose flexibility and power. Sorry to sound conceited, but I'll match any of your netbeans-created GUI's with one of my own, and mine will likely be better -- and I'm not all that good at this just yet.
    Much luck.

  • Lots of JPanels working from a single JFrame

    What I'm trying to do in this simple program is display a JPanel (called Panel1) in a JFrame(called MainFrame), and make it so that when you click the button that is displayed in Panel1 - the frame is updated and displays a new JPanel (called Panel2). Sounds like it should be quite simple, but I don't know how to update. Does dispose() have something to do with it? Thanks in advance.
    import java.awt.*;
    import javax.swing.*;
    public class MainFrame extends JFrame
    private int x;
    public MainFrame(){
    Panel1 panel1 = new Panel1(this);
    this.getContentPane().add(panel1);
    this.setSize(1024,770);
    this.setVisible (true);
    this.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
    public void redisplay(JPanel jp){
    this.getContentPane().add(jp);
    public static void main(String [] args){
    MainFrame mf = new MainFrame();
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Panel1 extends JPanel implements ActionListener
    private JButton jbutton;
    private MainFrame main;
    public Panel1(MainFrame ma)
    main = ma;
    try {
    jbInit();
    catch(Exception ex) {
    ex.printStackTrace();
    void jbInit() throws Exception {
    jbutton = new JButton("Go to Panel1");
    this.add(jbutton);
    jbutton.addActionListener(this);
    public void actionPerformed(ActionEvent e){
    if (e.getSource() == jbutton) {
    Panel2 panel2 = new Panel2(main);
    main.redisplay(panel2);
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    public class Panel2 extends JPanel implements ActionListener
    private JButton jbutton;
    private MainFrame main;
    public Panel2(MainFrame ma)
    main = ma;
    try {
    jbInit();
    catch(Exception ex) {
    ex.printStackTrace();
    void jbInit() throws Exception {
    jbutton = new JButton("Go to Panel1");
    this.add(jbutton);
    jbutton.addActionListener(this);
    public void actionPerformed(ActionEvent e){
    if (e.getSource() == jbutton) {
    Panel1 panel1 = new Panel1(main);
    main.redisplay(panel1);

    You need to remove the first panel before you add the new one, otherwise it will not be displayed properly.
    try:
    public void redisplay(JPanel newPanel) {
      getContentPane().removeAll();
      getContentPane().add(newPanel);
      // you may need this also:
      revalidate();
    // you can also try this:
    public class MainFrame extends JFrame {
      JPanel currPanel;
      public void redisplay(JPanel newPanel) {
        getContentPane().remove(currPanel);
        getContentPane().add(newPanel);
        // and you might need this:
        revalidate();
    public class

  • Please i need help with sound application! please?

    hey there people heres the deal I need to complete this before 5 today but im completely stumped...we have to make a sound file player with a swing interface I have it playing(kind of!) but where now...I would be forever in your debt as my masters degree hangs in the balance! de de duhhhh! cheers
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.event.*;
    import java.io.File;
    import java.io.IOException;
    import javax.sound.sampled.*;
    import javax.sound.sampled.AudioFormat;
    import javax.sound.sampled.AudioInputStream;
    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.Clip;
    import javax.sound.sampled.DataLine;
    import javax.sound.sampled.LineEvent;
    import javax.sound.sampled.LineListener;
    import javax.sound.sampled.LineUnavailableException;
    public class AudioPlayer extends JFrame implements ActionListener, ChangeListener{
    boolean playing;
    boolean looping;
    String filename = File.separator+"tmp";
    File selFile;
    Clip clip;
    JFileChooser fc = new JFileChooser();
    JButton btnOpen = new JButton("Open");
    JButton btnPlay = new JButton("Play");
    JButton btnStop = new JButton("Stop");
    JButton btnPause = new JButton("Pause");
    JButton btnLoop = new JButton("Loop");
    JSlider volume = new JSlider(SwingConstants.HORIZONTAL,0,100,0);
    JSlider panning = new JSlider(SwingConstants.HORIZONTAL,0,100,0);
    public AudioPlayer(){
    Container contentPane = getContentPane();
    contentPane.setLayout(new FlowLayout());
    contentPane.add(btnOpen);btnPlay.addActionListener(this);
    contentPane.add(btnPlay);btnPlay.addActionListener(this);
    contentPane.add(btnStop);btnStop.addActionListener(this);
    contentPane.add(btnPause);btnPause.addActionListener(this);
    contentPane.add(btnLoop);btnLoop.addActionListener(this);
    // Show open dialog; this method does not return until the dialog is closed
    fc.showOpenDialog(this);
    selFile = fc.getSelectedFile();
    volume.addChangeListener(this);
    panning.addChangeListener(this);
    volume.putClientProperty("JSlider.isFilled", Boolean.TRUE);
    volume.setPaintTicks(true);volume.setPaintLabels(true);
    volume.setMajorTickSpacing(20);volume.setMinorTickSpacing(10);
    contentPane.add(volume);
    panning.putClientProperty("JSlider.isFilled", Boolean.TRUE);
    panning.setPaintTicks(true);panning.setPaintLabels(true);
    panning.setMajorTickSpacing(20);panning.setMinorTickSpacing(10);
    contentPane.add(panning);
    addWindowListener(
    new WindowAdapter () {
    public void windowClosing(WindowEvent e){
    setVisible(false);
    public void actionPerformed(ActionEvent e){
    int returnVal = JFileChooser.APPROVE_OPTION;
    //Handle open file action.
    if (e.getSource() == btnOpen)
    System.out.println("FA1");
    returnVal = fc.showOpenDialog(AudioPlayer.this);
    if (returnVal == JFileChooser.APPROVE_OPTION)
    { selFile = fc.getSelectedFile();
    //This is where a real application would open the file.
    else
    if(e.getSource() == btnPlay)
    playAudio();
    public void stateChanged(ChangeEvent e)
    public static void main(String[] args)
    AudioPlayer audioPlayer = new AudioPlayer();
    audioPlayer.setSize(400,400);
    audioPlayer.show();
    public void playAudio ()
    playing = true;
    AudioInputStream audiosource = null;
    try
    audiosource = AudioSystem.getAudioInputStream(selFile);
    System.out.println("here");
    //System.out.println(audiosource.getFormat());
    DataLine.Info dataLineInfo = new DataLine.Info(Clip.class,audiosource.getFormat());
    clip = (Clip)AudioSystem.getLine(dataLineInfo);
    clip.open(audiosource);
    catch (UnsupportedAudioFileException e)
    catch (LineUnavailableException e)
    catch (IOException e)
    //catch (Exception e) {}
    if (looping)
    clip.loop(clip.LOOP_CONTINUOUSLY);
    else
    clip.loop(0);
    playing = false;
    }

    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import java.io.*;
    import javax.swing.event.*;
    import javax.sound.sampled.*;
    * Description of the Class
    *@author rsmazara
    *@created 28 February 2003
    public class AudioPlayer extends JFrame implements ActionListener, ChangeListener {
    File selFile;
    JFileChooser fc = new JFileChooser();
    JButton btnOpen = new JButton( "Open" );
    JButton btnPlay = new JButton( "Play >" );
    JButton btnStop = new JButton( "Stop" );
    JButton btnPause = new JButton( "Pause ||" );
    JCheckBox btnLoop = new JCheckBox( "Loop" );
    JSlider volume = new JSlider( SwingConstants.HORIZONTAL, 0, 100, 0 );
    JSlider panning = new JSlider( SwingConstants.HORIZONTAL, 0, 100, 0 );
    JLabel label = new JLabel( " " );
    public AudioPlayer() {
    Container contentPane = getContentPane();
    contentPane.setLayout( new FlowLayout() );
    btnOpen.addActionListener( this );
    contentPane.add( btnOpen );
    btnPlay.addActionListener( this );
    contentPane.add( btnPlay );
    btnPlay.addActionListener( this );
    contentPane.add( btnStop );
    btnStop.addActionListener( this );
    contentPane.add( btnPause );
    btnPause.addActionListener( this );
    contentPane.add( btnLoop );
    btnLoop.addActionListener( this );
    btnPlay.setEnabled( false );
    btnStop.setEnabled( false );
    btnPause.setEnabled( false );
    // Show open dialog; this method does not return until the dialog is closed
    // fc.showOpenDialog( this );
    // selFile = fc.getSelectedFile();
    volume.addChangeListener( this );
    panning.addChangeListener( this );
    volume.putClientProperty( "JSlider.isFilled", Boolean.TRUE );
    volume.setPaintTicks( true );
    volume.setPaintLabels( true );
    volume.setMajorTickSpacing( 20 );
    volume.setMinorTickSpacing( 10 );
    contentPane.add( volume );
    panning.putClientProperty( "JSlider.isFilled", Boolean.TRUE );
    panning.setPaintTicks( true );
    panning.setPaintLabels( true );
    panning.setMajorTickSpacing( 20 );
    panning.setMinorTickSpacing( 10 );
    contentPane.add( panning );
    contentPane.add( label );
    addWindowListener(
    new WindowAdapter() {
    public void windowClosing( WindowEvent e ) {
    setVisible( false );
    System.exit( -100 );
    public void actionPerformed( ActionEvent e ) {
    int returnVal = JFileChooser.APPROVE_OPTION;
    //Handle open file action.
    System.out.println( e.getActionCommand() );
    ///open
    if ( e.getSource() == btnOpen ) {
    System.out.println( "FA1" );
    returnVal = fc.showOpenDialog( AudioPlayer.this );
    if ( returnVal == JFileChooser.APPROVE_OPTION ) {
    selFile = fc.getSelectedFile();
    player = new Player( selFile );
    label.setText( "File loaded : " + selFile.getAbsolutePath() );
    btnPlay.setEnabled( true );
    btnStop.setEnabled( false );
    btnPause.setEnabled( false );
    //This is where a real application would open the file.
    } else {
    //play
    if ( e.getSource() == btnPlay ) {
    player.go( btnLoop.isSelected() );
    btnPlay.setEnabled( false );
    btnStop.setEnabled( true );
    btnPause.setEnabled( true );
    // playAudio();
    // pause
    if ( e.getSource() == btnPause ) {
    player.pause();
    btnPlay.setEnabled( true );
    btnStop.setEnabled( true );
    btnPause.setEnabled( false );
    if ( e.getSource() == btnStop ) {
    player.finish();
    btnPlay.setEnabled( true );
    btnStop.setEnabled( false );
    btnPause.setEnabled( false );
    public void stateChanged( ChangeEvent e ) {
    private Player player = null;
    public static void main( String[] args ) {
    AudioPlayer audioPlayer = new AudioPlayer();
    audioPlayer.setSize( 400, 400 );
    audioPlayer.show();
    * Description of the Class
    *@author rsmazara
    *@created 28 February 2003
    class Player {
    Clip clip;
    private java.io.File selectedFile = null;
    private boolean looping = false;
    public Player( File file ) {
    selectedFile = file;
    AudioInputStream audiosource = null;
    try {
    audiosource = AudioSystem.getAudioInputStream( selectedFile );
    System.out.println( "here" );
    //System.out.println(audiosource.getFormat());
    DataLine.Info dataLineInfo = new DataLine.Info( Clip.class, audiosource.getFormat() );
    clip = ( Clip ) AudioSystem.getLine( dataLineInfo );
    clip.open( audiosource );
    } catch ( UnsupportedAudioFileException e1 ) {
    e1.printStackTrace();
    } catch ( LineUnavailableException e2 ) {
    e2.printStackTrace();
    } catch ( IOException e3 ) {
    e3.printStackTrace();
    private boolean work = false;
    public void go( boolean loop ) {
    looping = loop;
    playAudio();
    public void finish() {
    clip.stop();
    public boolean isWorking() {
    return clip.isRunning();
    long pausePosition = ( long ) 0;
    public void pause() {
    pausePosition = clip.getMicrosecondPosition();
    clip.stop();
    public void restart() {
    clip.setMicrosecondPosition( pausePosition );
    playAudio();
    public void loop( boolean loop ) {
    looping = loop;
    private void playAudio() {
    if ( looping ) {
    clip.loop( clip.LOOP_CONTINUOUSLY );
    } else {
    clip.loop( 0 );

  • Adding sound to game application

    Can anyone assist me or provide a link as to how I can add sound to an application(non-applet)? In this case it is a space invaders clone tutorial; now I would like to add sound to when either the player or the aliens fire a laser. The problem is that I'm not sure how to do it. I initially tried using the AudioStream attribute from the sun.audio class but it did not work. Also I would like to add new images to the game background but when I add images to the panel, it does not appear when executed; the game loop I think affects this. Here is some code snippets:
    The initial setup function:
    public Game() {
              //ImagePanel p1 = new ImagePanel(new ImageIcon("City.png").getImage());
              // create a frame to contain our game
              JFrame container = new JFrame("Space Invaders 101");
              // get hold the content of the frame and set up the resolution of the game
              JPanel panel = (JPanel) container.getContentPane();
              panel.setPreferredSize(new Dimension(800,600));
              panel.setLayout(null);
              // setup our canvas size and put it into the content of the frame
              setBounds(0,0,800,600);
              panel.add(this);
              // Tell AWT not to bother repainting our canvas since we're
              // going to do that our self in accelerated mode
              setIgnoreRepaint(true);
              // finally make the window visible
              container.pack();
              container.setResizable(false);
              container.setVisible(true);
              // add a listener to respond to the user closing the window. If they
              // do we'd like to exit the game
              container.addWindowListener(new WindowAdapter() {
                   public void windowClosing(WindowEvent e) {
                        System.exit(0);
              // add a key input system (defined below) to our canvas
              // so we can respond to key pressed
              addKeyListener(new KeyInputHandler());
              // request the focus so key events come to us
              requestFocus();
              // create the buffering strategy which will allow AWT
              // to manage our accelerated graphics
              createBufferStrategy(2);
              strategy = getBufferStrategy();
              // initialise the entities in our game so there's something
              // to see at startup
              initEntities();
         }then the class for firing a shot:
    public class ShotEntity extends Entity {
         /** The vertical speed at which the players shot moves */
         private double moveSpeed = -300;
         /** The game in which this entity exists */
         private Game game;
         /** True if this shot has been "used", i.e. its hit something */
         private boolean used = false;
          * Create a new shot from the player
          * @param game The game in which the shot has been created
          * @param sprite The sprite representing this shot
          * @param x The initial x location of the shot
          * @param y The initial y location of the shot
         public ShotEntity(Game game,String sprite,int x,int y) {
              super(sprite,x,y);
              this.game = game;
              dy = moveSpeed;
          * Request that this shot moved based on time elapsed
          * @param delta The time that has elapsed since last move
         public void move(long delta) {
              // proceed with normal move
              super.move(delta);
              // if we shot off the screen, remove ourselfs
              if (y < -100) {
                   game.removeEntity(this);
          * Notification that this shot has collided with another
          * entity
          * @parma other The other entity with which we've collided
         public void collidedWith(Entity other) {
              // prevents double kills, if we've already hit something,
              // don't collide
              if (used) {
                   return;
              // if we've hit an alien, kill it!
              if (other instanceof AlienEntity) {
                   // remove the affected entities
                   game.removeEntity(this);
                   game.removeEntity(other);
                   // notify the game that the alien has been killed
                   game.notifyAlienKilled();
                   used = true;
    }The main game loop:
    public void gameLoop() {
              long lastLoopTime = System.currentTimeMillis();
              // keep looping round til the game ends
              while (gameRunning) {
                   // work out how long its been since the last update, this
                   // will be used to calculate how far the entities should
                   // move this loop
                   long delta = System.currentTimeMillis() - lastLoopTime;
                   lastLoopTime = System.currentTimeMillis();
                   // Get hold of a graphics context for the accelerated
                   // surface and blank it out
                   Graphics2D g = (Graphics2D) strategy.getDrawGraphics();
                   g.setColor(Color.black);
                   g.fillRect(0,0,800,600);
                   // cycle round asking each entity to move itself
                   if (!waitingForKeyPress) {
                        for (int i=0;i<entities.size();i++) {
                             Entity entity = (Entity) entities.get(i);
                             entity.move(delta);
                   // cycle round drawing all the entities we have in the game
                   for (int i=0;i<entities.size();i++) {
                        Entity entity = (Entity) entities.get(i);
                        entity.draw(g);
                   // brute force collisions, compare every entity against
                   // every other entity. If any of them collide notify
                   // both entities that the collision has occured
                   for (int p=0;p<entities.size();p++) {
                        for (int s=p+1;s<entities.size();s++) {
                             Entity me = (Entity) entities.get(p);
                             Entity him = (Entity) entities.get(s);
                             if (me.collidesWith(him)) {
                                  me.collidedWith(him);
                                  him.collidedWith(me);
                   // remove any entity that has been marked for clear up
                   entities.removeAll(removeList);
                   removeList.clear();
                   // if a game event has indicated that game logic should
                   // be resolved, cycle round every entity requesting that
                   // their personal logic should be considered.
                   if (logicRequiredThisLoop) {
                        for (int i=0;i<entities.size();i++) {
                             Entity entity = (Entity) entities.get(i);
                             entity.doLogic();
                        logicRequiredThisLoop = false;
                   // if we're waiting for an "any key" press then draw the
                   // current message
                   if (waitingForKeyPress) {
                        g.setColor(Color.white);
                        g.drawString(message,(800-g.getFontMetrics().stringWidth(message))/2,250);
                        g.drawString("Press any key",(800-g.getFontMetrics().stringWidth("Press any key"))/2,300);
                   // finally, we've completed drawing so clear up the graphics
                   // and flip the buffer over
                   g.dispose();
                   strategy.show();
                   // resolve the movement of the ship. First assume the ship
                   // isn't moving. If either cursor key is pressed then
                   // update the movement appropraitely
                   ship.setHorizontalMovement(0);
                   if ((leftPressed) && (!rightPressed)) {
                        ship.setHorizontalMovement(-moveSpeed);
                   } else if ((rightPressed) && (!leftPressed)) {
                        ship.setHorizontalMovement(moveSpeed);
                   // if we're pressing fire, attempt to fire
                   if (firePressed) {
                        tryToFire();
                   // finally pause for a bit. Note: this should run us at about
                   // 100 fps but on windows this might vary each loop due to
                   // a bad implementation of timer
                   try { Thread.sleep(10); } catch (Exception e) {}
         

    for basic sounds, you can use the JavaSound API.
    http://java.sun.com/docs/books/tutorial/sound/index.html
    There are plugin libraries available that add MP3 and OGG support to it.
    http://www.javazoom.net/index.shtml

  • A Grow Box for a JFrame

    I am this >||< (font size 8) close to getting this JGrowBox class thing to work exactly the way I want it to, and then, everybody can have a nice little grow box thingie to "attatch" to their JFrames. Ooooh.
    I have three problems. First, if the user tries to resize the frame normally (grabs the very corner of the JFrame) then the JFrame resizes in its normal ugly way, without repainting its components (which means that the JGrowBox thing just stays where it is, which looks stupid.) Second, if the user grabs the actual JGrowBox the way you can with all other stupid Windoze programs, the JFrame flickers horribly, and the CPU goes nuts. Third, I use static byte array representations of the GIF images. This is kinda lame. I'm guessing all the cool Java widgets use Java2D somehow.
    The dimensions used for the customized JComponent are specific to the arrangment of the rest of the layout. The JGrowBox is actually in the BorderLayout.EAST of a 18-pixel tall JPanel "status bar" thingie, which is in the BorderLayout.SOUTH of the contentPane. I didn't feel like going through the hassle of getting the thing to be universally positioned at the bottom-right of the parent JFrame, regardless of layout.
    The images are just a 16x16 screen captures of the Windows 2000 and Windows XP grow boxes, respectively, with the window grey replaced with black and black set as the transparent color, and then sort of converted into a static byte array. I suppose it might be a bit more space-saving to just use Java2D to draw out all the pixels and stuff, but I hate doing that kinda crap.
    Code:
    * JGrowBox.java
    * Created on July 28, 2005, 1:54 PM
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import javax.swing.*;
    import javax.swing.event.*;
    * @author [email protected]
    public class JGrowBox
        extends JComponent {
        // the associated JFrame window parent of the grow box
        private JFrame parent = null;
        // where the user clicked the mouse to resize using the grow box
        private Point p0 = null;
        // the image of the grow box thinga-ma-jigger
        private Image image = null;
        /** Creates a new instance of JGrowBox */
        public JGrowBox(final JFrame parent) {
            this.parent = parent;
            // get the name of the operating system
            String OS_NAME = System.getProperty("os.name");
            // anybody got GIFs for KDE or GNOME?
            if (OS_NAME.equals("Windows 2000")) {
                image = new ImageIcon(WINDOWS_2000_GROW_BOX.BYTES).getImage();
            else if (OS_NAME.equals("Windows XP")) {
                image = new ImageIcon(WINDOWS_XP_GROW_BOX.BYTES).getImage();
            // this stuff is specific to a given arrangement
            setSize(new Dimension(18, 15));
            setPreferredSize(new Dimension(18, 15));
            setMaximumSize(new Dimension(18, 15));
            setMinimumSize(new Dimension(18, 15));
            setFocusable(false);
            // getting the first mouseClick and changing the cursor and stuff
            addMouseListener(new MouseAdapter() {
                public void mouseEntered(MouseEvent e) {
                    parent.getContentPane().setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR));
                public void mouseExited(MouseEvent e) {
                    parent.getContentPane().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                public void mousePressed(MouseEvent e) {
                    if (e.getButton() == MouseEvent.BUTTON1) {
                        p0 = e.getPoint();
                public void mouseReleased(MouseEvent e) {
                    if (!contains(e.getPoint())) {
                        parent.getContentPane().setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
            // when the user drags the mouse, resize the parent JFrame (ugly!)
            addMouseMotionListener(new MouseMotionAdapter() {
                public void mouseDragged(MouseEvent e) {
                    Point p1 = e.getPoint();
                    parent.getContentPane().setCursor(Cursor.getPredefinedCursor(Cursor.SE_RESIZE_CURSOR));
                    Rectangle bounds = parent.getBounds();
                    int x = bounds.width + (p1.x - p0.x);
                    int y = bounds.height + (p1.y - p0.y);
                    Point p2 = new Point(x, y);
                    int xMax = Toolkit.getDefaultToolkit().getScreenSize().width;
                    parent.setSize(Math.min(p2.x, xMax), p2.y);
            // hide the grow icon when the parent window is maximized
            parent.addComponentListener(new ComponentAdapter() {
                public void componentResized(ComponentEvent e) {
                    if (parent.getExtendedState() == JFrame.MAXIMIZED_BOTH) {
                        setVisible(false);
                    else {
                        setVisible(true);
        public void paintComponent(Graphics g) {
            if (image != null) {
                g.drawImage(image, 3, 3, this);
        public boolean contains(Point p) {
            Rectangle r = getBounds();
            return (p.x >= 0 && p.x <= r.width &&
                    p.y >= 0 && p.y <= r.height);
    class WINDOWS_2000_GROW_BOX {
        public final static byte[] BYTES = {
      71,   73,   70,   56,   57,   97,   16,    0,   16,    0,   -9,    0,    0,    0,    0,    0,
      -1,   -1,   -1,  -44,  -48,  -56, -110, -116, -106, -100, -102,  -69,    0,    0,   -1,    0,
       0, -128, -118, -103,  -35,  115,  126,  -96,   10,   36,  106,   10,   35,  103,    9,   32,
      95,   11,   37,  107,   13,   39,  109,   35,   54,  106,   10,   36,  105,    8,   27,   77,
      12,   39,  108,   14,   40,  109,   15,   42,  110,   15,   41,  110,   16,   42,  111,   17,
      44,  112,   17,   43,  112,   18,   45,  113,   19,   46,  114,   20,   47,  115,   15,   35,
      84,   21,   48,  116,   21,   48,  115,   22,   49,  116,   23,   50,  117,   24,   51,  118,
      25,   52,  119,   27,   54,  120,   28,   55,  121,   29,   56,  122,   30,   57,  123,   31,
      58,  124,   32,   59,  125,   34,   61,  126,   36,   63, -128,   37,   64, -127,   38,   65,
    -126,   30,   58,  123,   32,   60,  125,   33,   61,  126,   34,   62,  127,   39,   67, -125,
      41,   70, -123,   40,   68, -125,   41,   69, -124,   42,   70, -123,   43,   71, -122,   44,
      72, -121,   45,   74, -120,   45,   73, -120,   46,   75, -119,   47,   75, -118,   48,   77,
    -117,   49,   78, -116,   48,   76, -118,   50,   79, -115,   51,   80, -115,   52,   81, -114,
      53,   82, -113,   54,   83, -112,   54,   83, -113,   55,   84, -111,   56,   85, -110,   56,
      85, -111,   57,   86, -110,   58,   87, -109,   59,   88, -108,   60,   89, -107,   61,   91,
    -106,   61,   90, -107,   62,   91, -106,   63,   93, -104,   63,   92, -105,   64,   93, -104,
      65,   94, -103,   66,   95, -102,   67,   96, -101,   68,   98, -100,   69,   99,  -99,   68,
      97, -101,   70,  100,  -99,   72,  102,  -97,   71,  101,  -98,   73,  104,  -96,   73,  103,
    -96,   74,  104,  -95,   75,  105,  -94,   76,  107,  -93,   77,  108,  -92,   77,  107,  -92,
      76,  106,  -94,   78,  109,  -91,   79,  110,  -91,   80,  111,  -90,   82,  113,  -88,   81,
    112,  -89,   83,  114,  -87,   84,  115,  -86,   85,  116,  -85,   87,  118,  -84,   89,  120,
    -82,   88,  119,  -83,   90,  121,  -81,   89,  120,  -83,  105, -115,  -53,   91,  123,  -80,
      93,  125,  -78,   92,  123,  -80,   91,  122,  -81,   93,  124,  -79,   95,  126,  -77,   94,
    125,  -78,   96,  127,  -76,   97, -128,  -76,   98, -126,  -75,   98, -127,  -75,  100, -125,
    -73,  100, -124,  -73,   99, -126,  -74,  101, -123,  -72,  103, -121,  -70,  102, -123,  -71,
    102, -122,  -71,  105, -119,  -68,  104, -120,  -69,  107, -117,  -67,  106, -118,  -68,   31,
      59,  102,   36,   64,  104,  107, -116,  -66,  108, -115,  -66,  110, -113,  -64,  109, -114,
    -65,  112, -111,  -62,  111, -112,  -63,  113, -110,  -61,  112, -112,  -63,  114, -109,  -61,
    116, -107,  -59,  115, -109,  -60,  115, -108,  -60,  118, -105,  -57,  117, -106,  -58,  120,
    -103,  -55,  119, -104,  -56,  121, -102,  -54,  119, -104,  -57,  122, -101,  -54,  121, -102,
    -55,  124,  -99,  -52,  123, -100,  -53,  125,  -98,  -51, -117,  -83,  -32,   72,  124,  -61,
    126,  -96,  -50,  124,  -99,  -53,  126,  -97,  -51, -127,  -93,  -48, -128,  -95,  -49, -125,
    -91,  -46, -126,  -92,  -47, -123,  -89,  -44, -124,  -90,  -45, -121,  -87,  -42, -122,  -88,
    -43, -118,  -84,  -40,  106,  -98,  -36,   97, -119,  -72, -123,  -85,  -38, -120,  -85,  -41,
    -117,  -82,  -39, -119,  -84,  -41, -114,  -80,  -37, -115,  -81,  -38, -116,  -82,  -39, -112,
    -77,  -35, -113,  -79,  -36, -110,  -75,  -33, -111,  -77,  -34, -111,  -76,  -34, -107,  -72,
    -30, -108,  -73,  -31, -109,  -74,  -32, -106,  -71,  -30, -107,  -72,  -31, -104,  -69,  -28,
    -105,  -70,  -29, -102,  -67,  -26, -103,  -68,  -27,  109,  -93,  -34, -100,  -65,  -25, -101,
    -66,  -26, -102,  -67,  -27,  -97,  -61,  -22,  -98,  -63,  -23,  -98,  -62,  -23,  -99,  -64,
    -24,  -95,  -59,  -20,  -96,  -61,  -21,  -93,  -57,  -18,  -95,  -60,  -21,  -93,  -58,  -19,
    -97,  -73,  -46,  -95,  -72,  -46,   45,   88, -126,   74,  122,  -87,  -94,  -58,  -20,  -91,
    -55,  -17,  -90,  -54,  -16,  -70,  -52,  -34,   78,  -99,  -29,   74, -114,  -51,  109,  -71,
      -9,  -85,  -52,  -25, -124,  -81,  -47,   65, -115,  -62,  124,  -78,  -40,  -86,  -43,  -12,
    -77,  -63,  -53,  105, -127, -113,   67,  -98,  -51,   73,  -86,  -38,  103,  -74,  -33,   77,
    -70,  -21,  104,  -57,  -23,  -72,  -27,  -13, -127,  -45,  -23, -104,  -33,  -13,  -61,  -18,
      -6, -111,  -36,  -16, -101,  -49,  -37, -101,  -34,  -25,  127,  -47,  -37,  -85,  -27,  -40,
    -111,  -28,  -65,  -99,  -21,  -57,    0, -128,    0,  -48,   -8,  -51,   -1,   -1,    0, -128,
    -128,    0,  -69,  -73,  -97,  -83,  -99,  105,  123,  110,   81,  -87,  -91, -100,   -1,    0,
       0, -128,    0,    0, -110, -118, -118, -128, -128, -128,   64,   64,   64,   33,   -7,    4,
       1,    0,    0,    0,    0,   44,    0,    0,    0,    0,   16,    0,   16,    0,    0,    8,
      59,    0,    1,    8,   28,   72,  -80,  -96,  -63, -125,    8,   19,    6,   72,   88,   48,
    -128,   63, -122,    3,   29,   62, -124,   40,   17,   34, -128, -118,   11,   21,   -6,  123,
    -24,   80,   35,  -57, -115,    8,   49, -126,   60,   40, -110,  -93,  -63, -110,   23,   39,
      70,    4, -119,  114,  -27,  -57, -105,   22,   99,   50,   12,    8,    0,   59
    class WINDOWS_XP_GROW_BOX {
        public final static byte[] BYTES = {
      71,   73,   70,   56,   57,   97,   16,    0,   16,    0,   -9,    0,    0,   -8,  -70,   43,
    -45,  -94,  -97,    0,   90,  -20,  -39,  -39,  -40,    2,  106,   -2,  -26,  111,   82,  113,
    111,  100,  -11,  -11,  -15,  -14,  -14,  -18,  121,  -98,  -66,  -52,  -51,  -53, -111, -103,
    -48,  111,  114,  -78,  -83,  -80,  -45,  -13,  -21,  -76,  -30,  -36,  -53,  -74,  -57,   -8,
       0,    0,    0,    1,  -79,    3,  -39,  -30,   -7,  -98,  -74,  -41,  -36,   10,   25,   73,
    124,  -10,   -2,   -5,  -11,  -32,   77,   47,    0,   75,  -30,  -91,  -90,  -91,  -28,  -24,
      -8,  101,  -79,   -8,   53,  112,  -12,   83, -118,   -9, -110,  -44,   -8,  -84,  -88, -103,
       1,   19, -117,   62, -106,   -1,  -17,  -19,  -34,    3,  101,  -15,   33, -105,  -76,  -82,
    -70,  -19,  -77,  -14,   -5,   -7,  -56,   76,    0,   90,  -12,  -15,  -17,  -30,  -44,  -37,
      -8,  120,  -56,  -21,   20,   72,  -69,    0,  -98,  -57,    0,   60,  116,  -65,  -63,  -65,
       1,   68,  -48,    1,  -37,    0,   81,  -90,   -8,  -74,  123,    0,  -28,  -28, -109,  -51,
    -42,   -7,  -59,  -59,  -59,   -8, -103,  116, -105,  -78,  -17,  -97,  -95,  -98, -122, -119,
    -65,  -10,  -84,   76,   75,   75,   74,    1,   67,  -49, -122, -126, -122,    3,  113,   -1,
       8,   85,  -35,  104, -107,  -11, -100, -103, -100,  -33,  -33,  -35,    0,   30,  -95,  -86,
      47,   10,  -20,  -23,  -40,  -38,  -43,  -61,   -7,   -7,   -7,  -35,  -75,  -59,   44,   44,
      43,  -17,  -18,  -13,   43, -112,   -1,    0,   61,  -36,   98,   98,   98,  -63,  -59,  -27,
      -3,  -49,  108,    6,   44,  -86,  -45,  -59,  -80,   -2,   -3,   -6,  -28,  -27,  -28,   50,
    106,  -63,  -79,  -77,  -80,  -61,  -49,   -7,   85,  -68,  -44,  -16,  -45,  -18,   35,   89,
    111, -104,  -49,  -52,   53,  -84,  -56,  -86,  -85,  -69,    0,   88,  -26, -113, -115, -114,
      65, -110,  -89,   74,  -83,   96,  -70,  -70,    0,  -77,  118, -111,   -5,  -17,  -41,  -14,
    -13,   -8,  -19,  -21,  -26,   21, -124,  -24,  -45,  -41,  -19,    0,   72,  -15,  124,  121,
    119,  -94,  -98, -105,   22,  106,  -18,  -28,  -12,   -5,  -21,  -52,  -67,    6, -124,   92,
      -4,  -36, -111,    0,   85,  -22,  -99, -106,  -74,  -54, -114,   82,    0,   83,  -31,   97,
    -85,  -70,  -37,  -35,  117,  -19,  -28,  -58,   -5,   -9,  -12,  120,  -72,  -53,   18,  -92,
    -55,   -1,   -1,   -1,   81,  -22,   70, -112,   -7, -123,    7,   49,  -39,  105,   40,   19,
    -11,   -4,   -5,   -5,  -10,  -20,  -72,   94,  108,    3,   54,  -66,  -71,  -71,  -70,  120,
    -84, -121,    1,   97,  -21,    8,   49,  -39,  -24,  -25,  -25,  -55,  -49,  -22,  -11,  -13,
    -27,   -5,  -62,   59,   32, -122,   -2,    0,   54,  -21,    7,  120,  -92,  105, -107,  -52,
      36,  106,  -11,  -20,  -20,  -18,   -5,  -10,  -25,   34,  120,   -7,    0,   25,  -49,  -69,
    -67,  -36,   27,   94,  -27,   80, -102, -100,  -23,  -70,   83,  -21, -124,   89,    2,  107,
    -12,   80,  -80,  -90,  106, -114,  -96,   44,   89,  -60,    1,  100,   -7,    0,   81,  -27,
      -8,   -7,   -3,  -46,  -61,  -37,    0,   38,  -59,  -72,  -76,  -94,  -25,  -31,  -37,   39,
      96,  -27,   -6,  -63,   14,   -4,  -13,   -3, -109,  -92,  -73,    0,   38,  -45,   41, -103,
    -56,   27,   90,  -15,  -59,  -39,  127,  -74,  -67,  -68,   23,   85,  -33,   15,   92,  -25,
      10,  102,  -12,   -2,  -20,  -22,  -23,  -26,  -33,    3,   62,  -56,    6,   77,  -42,  -16,
    -16,  -21,    4,   84,  -25,  -24,  -27,  -45,   -4,   -4,   -5,    0,   55,  -45,  -96,  -64,
      43,    0,   85,  -27,   -1,  -17,  -53,  -33,  -28,  -50,    6,   88,  -28,  -31,  -26,  -24,
       0,   96,   -8,    0,   84,  -29,    0,  101,   -3,   -9,  -17,  -25,    0,   96,   -4,  -57,
    -53,   45,   -2,   -5,  -18,   -2,   -2,   -2,  -64,  -70,  -84,   63,   64,   61,  -11,  -12,
    -36,  -48,  -44,   80,  -69,  -85,  -66,  -60,  -58,   30,    0,  123,    2,    1,  114,  -34,
      -5,   -5,  -27, -110, -111, -107,   -9,  -21,  -32,  -97, -105, -127,   -6,  -23,   78,   -7,
    -26,   96,   58, -104,  -26,  -46,  -45,  -46,   42, -107,  -22,   -4,   -4,   -1,   -1,   -1,
    -83, -112,   -1,   -1,   50, -119,   -3,   32,   45,   52,   17,   20,   18,  108,  108,  108,
    -40,  -68, -113,   73, -123,  -43,   33, -115,  -34,  -15,  -14,  -23,   70,  -87, -109,  -13,
    -29,  -30,   21,  126,  -32,    3,  104,   -6,   -3,   -2,   -2,  -65,  -36,  -57,   21,  111,
      -9,   -1,   -2,   -3,   37,  -20,   32,   17,   78,  -33,  -21,  -24,  -32,   11,  104,   -9,
      14,   80,  -19,   -8,   -4,   -3,   -2,   -5,   -5,  -42,  -48,  -59,  -11,  -11,  -22,  -48,
    -33, -107, -122, -112,  105,  112,   89, -118,  -21,  -24,  -40,  126,  -92,  -14,  -97,  -96,
    -53,  -33,  -62,  -24,  -49,  -79,   59,  127,  109,   76,    7,   79,  -22,   33,   -7,    4,
       1,    0,    0,   17,    0,   44,    0,    0,    0,    0,   16,    0,   16,    0,    0,    8,
      61,    0,   35,    8,   28,   72,  -80,  -96,  -63, -125,    8,   19,   42,   36,   72, -118,
    -44,  -62, -127,   13,   -7,   60,   20,  -56,   71,  -30,  -60, -123,   13,    5,  102,   76,
      24,   49,   66,  -57, -124,   21,   41,   90,  -68,   88,  112,  -93,   73, -121,   37,   73,
      73,  -20,   -8, -111,   96,  -56,    8,   47,   95, -110, -100,   25,   33,   32,    0,   59
    }

    Yes, <expletive deleted>, I know what Google is.You need to calm down.I was perfectly calm. You're the one saying "Oh, but maybe you don't know what a "google" is.", which intended or not, sounds like you're calling me a jackass for not looking it up myself. Nevermind the fact that you said in the post before that that you didn't even know what it was called. So why should I assume that searching the web for "grow box" is going go give me any results at all that have to do with what you're trying to do?
    Hmm, perhaps you are just being argumentative, and
    wasting my time, but I'll assume that there are
    enough people out there like you who don't understand
    what the purpose of that doohickey in the southeast
    corner of a window is to make responding to your
    questions worth my time. I'm not doing it to waste your time. I'm quite sure I've never seen what you linked to on an application before. At least not like what that link showed. If you had said, for example, like Internet Explorer has that little larger box in the lower right corner which acts as a larger handle for window resizing, then I might have understood you from the start.
    By the way, are you
    suggesting by your question that it is perhaps
    unnecessary to fulfill the expectations of the end
    user with respect to the graphical user interface of
    a Java program, just because the given defacto Java
    component already has very nearly the bare minimum
    functionality expected of a comparable gui component
    that can be found in any other relatively advanced
    development kit?I would expect that a frame-like container component that supports manual resizing by the user would supply some location to click to initiate that resize. How is up to the component.
    Okay, so why would you need a handle to resize the
    frame?
    Reason #1: Because it aids the user in resizing the
    window. It's a bigger, albeit not by much, area on
    the screen for which the user can aim for in the
    mouse movement action to "grab" onto a portion of the
    current window in order to resize it, reducing the
    amount of time wasted on window arrangement.As mentioned above, if something like what IE has, or Netscape or FireFox has in the lower right, then fine.
    Reason #2: Because I'll bet you dollars to donuts
    that the web browser you are using right now to view
    this rapidly decaying topic has one. Shouldn't your
    program be at least as good as, say,
    IExploder? Why not at least try to make your
    Java program seem like it didn't just fall off the
    Swing turnip truck?I wouldn't use the terms "at least as good as" and IE in the same sentence. But that's just me. But as I mentioned above, I don't think you were clear on what you were talking about.
    You started by saying "grow box" like this was some common name for something assuming everyone would know what you were talking about. Then when asked, you admitted you didn't know what it was really called, which as mentioned, I think precludes one from "googling" that term, as the results, IMO, can be assume to not necessarily be what you are talking about. Then you post a specific link to a site that you say is more or less what you have in mind, but that's refering to very old Mac applications as an example, instead of (as in your most recent post) just refering to a very common modern application as an example.
    Reason #3: Because, maybe it looks cooler that way.
    I mean, geez, man. You don't have to
    o use it. It was just an idea. Gawd.I think you need to calm down. If you can't be more clear initially what you're talking or give modern references to site examples, then you shouldn't expect everyone on a text-only forum can read your mind and figure out what you really are looking for.
    Addressing the second problem I was having with this
    class, adding this line:
    System.setProperty("sun.awt.noerasebackground",
    ound", "true");
    gets rid of the flicker, but not the performance hit.
    Got this from the misnamed not_a_genius in "Re:
    : Transparent windows."
    (http://forum.java.sun.com/thread.jspa?threadID=391403
    &messageID=3067048#3067048).http://www.javadesktop.org/forums/thread.jspa?threadID=6437&tstart=15
    You basically are either going to have to live with the performance hit or the flicker, from what I can see. At least til Java 6 next year. Or you can check
    https://swinglabs.dev.java.net/
    and see if they have a fix that is backwards compatible with Java 1.5. I thought I heard said that they made something available to fix the "gray rectangle" problem... I could be wrong about that, though.
    Anyway, for real info, you can read thru:
    http://weblogs.java.net/blog/chet/archive/2005/04/swing_update_no_1.html

  • Can anyone help with my sound query?

    Hi all
    I need to load from a file a sound clip and for it to play when a button is pressed- the difficult bit is without referencing Applet.
    Can anyone help?
    Thanks

    import java.awt.*;
    import java.applet.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.net.*;
    import java.io.*;
    public class JFrameTest extends JFrame implements ActionListener {
         public JFrameTest() {
         super("Hey");
              setSize(100,100);
              JButton btn = new JButton("Press to play");
              btn.addActionListener( this );
              getContentPane().add( btn );
         public void actionPerformed( ActionEvent ae ) {
              try {
             URL url = new File("1.wav").toURL();
                   AudioClip ac = Applet.newAudioClip(url);
                   ac.play();
        } catch (MalformedURLException e) {
                   e.printStackTrace();
         public static void main(String[] args) {
              JFrameTest f = new JFrameTest();
              f.show();
    }Those tab-indentations get really messed up...

  • Adding a Key Binding Globally (to an entire JFrame)

    Hi, all. I'm trying the ever-so-common task of adding a global key binding to my little Swing app. I just wrote a very basic image converter for an obscure multi-frame format and one of the users requested that I add a simple feature: when control-N is pressed, the a new document is created (just as if the user had selected New from the File menu).
    I've read the Swing keybinding tutorial and I've tried to write a method to neatly contain the operation. The method is as follows:
        public static void setKeystrokeForAction(JFrame jframe, KeyStroke keystroke, Action action)
            jframe.getRootPane().getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(keystroke, action.getValue(Action.NAME));
            jframe.getRootPane().getActionMap().put(action.getValue(Action.NAME), action);
        }This doesn't seem to work. I was under the impression that this would somehow allow any component focused in the frame to respond to the specified KeyStroke (in this case, control-N) and react by executing the Action provided (in this case, an action which calls the new document method in my application). However, I press control-N with various focused components and nothing happens.
    I know that the Action is sound because selecting the File : New item (which uses the same Action object) works just fine. The KeyStroke is constructed as follows:
    KeyStroke.getKeyStroke(KeyEvent.VK_N, KeyEvent.CTRL_DOWN_MASK)What am I missing?
    Thanks!

    Don't know why its not working. Its works fine for me in this example:
    http://forum.java.sun.com/thread.jspa?forumID=57&threadID=312780
    Although the example uses WHEN_IN_FOCUSED_WINDOW I also tested it with WHEN_ANCESTOR... and it still worked fine.

  • Why doesnt a sound play when I change the path?

    Hi. I am trying to play a background sound in my program and so far, after searching and reading lots of posts I finally have a "TaDa" sound playing once when the program starts. But what I want is a sound to be looped everytime I start a program. That sound will be in the same folder as the program.
    This is the code that I put in public static void main() to play the sound:
    public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    java_testt b = new java_test();
    b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    b.startApp();
    private void startApp()
    {playStartupSound();}
    private void endApp() {System.exit(0);}
    private void playStartupSound() {
    Runnable soundPlayer = new Runnable() {
    public void run() {
    try {                                                                                    
    File tadaSound = new File(System.getenv("windir") + "/" + //This is the windows tada sound. All I want is
    "media/tada.wav"); //to change the path to another sound
    AudioInputStream audioInputStream = AudioSystem
    .getAudioInputStream(new FileInputStream(tadaSound));
    AudioFormat audioFormat = audioInputStream
    .getFormat();
    DataLine.Info dataLineInfo = new DataLine.Info(
    Clip.class, audioFormat);
    Clip clip = (Clip) AudioSystem
    .getLine(dataLineInfo);
    clip.open(audioInputStream);
    clip.start();
    } catch (Exception e) {
    e.printStackTrace();
    Thread soundPlayingThread = new Thread(soundPlayer);
    soundPlayingThread.start();
    Does anyone know how to choose another sound in the same folder as java_test and make it work with this code because when I change the ath it doesnt run.
    Thanks.

    Please put your code between the code tags. It's much better readable then.
    public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    java_testt b = new java_test();
    b.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    b.startApp();
    private void startApp()
    {playStartupSound();}
    private void endApp() {System.exit(0);}
    private void playStartupSound() {
    Runnable soundPlayer = new Runnable() {
    public void run() {
    try {
    File tadaSound = new File(System.getenv("windir") "/" //This is the windows tada sound. All I want is
    "media/tada.wav"); //to change the path to another sound
    AudioInputStream audioInputStream = AudioSystem
    .getAudioInputStream(new FileInputStream(tadaSound));
    AudioFormat audioFormat = audioInputStream
    .getFormat();
    DataLine.Info dataLineInfo = new DataLine.Info(
    Clip.class, audioFormat);
    Clip clip = (Clip) AudioSystem
    .getLine(dataLineInfo);
    clip.open(audioInputStream);
    clip.start();
    } catch (Exception e) {
    e.printStackTrace();
    Thread soundPlayingThread = new Thread(soundPlayer);
    soundPlayingThread.start();
    }

  • Swing Components not displaying in a JFrame

    Hi,
    I have a JFrame with a couple of JLabels, JButtons etc. and a Choice Combo Box
    my problem is that when i run the program the only component that gets displayed at first is Choice and in order for me to see the swing components i have to roll over them with my mouse and the JLabels dont even display when i do that..
    Does anyone know how i can fix this please?
    here is my code
    import java.awt.*;
    import java.awt.event.*;
    import java.lang.*;
    import java.awt.Image.*;
    import java.io.*;
    import java.net.*;
    public class ImageViewerAnim extends JFrame {
         private JLabel perc, scale;
         private JTextField inPercent;
         private JButton draw, muteOn;
         private JPanel sPanel;
         private String[] pics = {"Earth", "Moon", "Jupiter", "Pluton", "Neptun"};
         private String[] picsFile = {"images/earth.gif", "images/moon.gif", "images/jupiter.jpg", "images/pluton.jpg", "images/neptun.jpg"};
         private String[] soundsFile = {"sounds/tada.wav", "sounds/notify.wav", "sounds/ding.wav", "sounds/chimes.wav", "sounds/chimes.wav"};
         private Choice ch;
         private Image pic;
         private AudioClip sound = null;
         private int scaleAm = 0;
         private int origScale = 500;
         private int finalScale = 0;
         private boolean proceed = true;
         public ImageViewerAnim() {
              Container c = getContentPane();
              c.setLayout(new BorderLayout());
              sPanel = new JPanel();
              ch = new Choice();
              for(int i = 0; i < pics.length; ++i) {
                   ch.add(pics);
              scale = new JLabel("Scale");
              perc = new JLabel("%");
              inPercent = new JTextField(5); // scale value input field
              draw = new JButton("Draw");
              draw.setBorder(BorderFactory.createEtchedBorder());
              draw.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        int index = 0;
                        index = ch.getSelectedIndex();
                        pic = null;
                        repaint();
                        pic = (Toolkit.getDefaultToolkit().getImage(picsFile[index]));
                        try{
                        File f = new File(soundsFile[index]);
                        sound = Applet.newAudioClip(f.toURL());
                        }catch(MalformedURLException mfe) {
                             mfe.printStackTrace();
                        if(!inPercent.getText().equals("")) {
                             scaleAm = Integer.parseInt(inPercent.getText()); // get the scale amount from the user
                             finalScale = ((origScale * scaleAm)/100); // calculate the final scale amount based on what the user entered
                        }else {
                             finalScale = origScale; // default to original size of the image if no value for scale was entered
                        // creates a scaled instance of an image and takes the amount of scale as an argument
                        repaint();
                        sound.loop();
              muteOn = new JButton("Mute On");
              muteOn.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        sound.stop();
                        muteOn.setText("MuteOff");
              sPanel.add(ch);
              sPanel.add(scale);
              sPanel.add(inPercent);
              sPanel.add(perc);
              sPanel.add(draw);
              sPanel.add(muteOn);
              c.add(sPanel, BorderLayout.SOUTH);
              repaint();
    public void paint(Graphics g) {
         if(pic!=null) {
              g.drawImage(pic,0,0,this);
    public static void main(String args[]) {
         ImageViewerAnim app = new ImageViewerAnim();
         app.setSize(500,500);
         app.setVisible(true);
         app.setDefaultCloseOperation(EXIT_ON_CLOSE);
         app.show();
    thank you in advance
    Ivo

    for future reference
    i was able to fix this by adding
    super.paint(g);in the first line of my paint method
    Ivo

  • Sound Application Problems

    Hello,
    Ive been working on a small sound application that just plays music when is starts up. Ive got this:
    import java.applet.AudioClip;
    import java.applet.Applet;
    import javax.swing.*;
    import java.net.URL;
    class Soundf extends JFrame {
         public Soundf() {
              super("Sound");
              AudioClip p = null;
              try {
                   p = Applet.newAudioClip(new URL(new URL("file:z3-light_world1.mid"), "z3-light_world1.mid"));
              catch(Exception e){
                   System.out.println("error");}
              p.play();
              setVisible(true);
    class Sound {
         public static void main(String args[]) {
              JFrame f = new Soundf();
    }I dont get any errors, but it just doesnt play the mid file. Please help.

    p = Applet.newAudioClip(new URL(new
    URL("file:z3-light_world1.mid"),
    "z3-light_world1.mid"));The contructor URL( URL, String) (eg URL( new URL( "http://www.example.com" ), "index.html" )creates a URL of http://www.example.com/index.html.

  • How to Play a sample sound using Java

    Hi,
    I have an mp3 music files in database. When a user chooses a particular button, all the songs are fetched from the database.
    I have two buttons namely, 'Buy' and 'Play Sample'. If I click the 'Play Sample' button, a sample of the song has to be played (not the full song). If the user likes the sample, he can buy the full song.
    My question is how to achieve the 'Play Sample' using Java Swings and Sound. I have googled, but not find any solutions. Please provide me an example or link.
    Thanks in advance.

    HI
    Actually i am trying to create a JFrame which plays an mp3 music file
    with the help of play and stop buttons in it ...
    i splitted the frame into two
    i want a music file list in the first frame (JComboBox)
    and want to have play and stop button in the second frame .
    i had tried out some code in which the frame part is fine ,,,
    but i am not knowing how to play the file with those buttons ...
    here is the code and plz help me to move further ...
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JSplitPane;
    public class AudioFile extends JFrame {
        public AudioFile() {
            setTitle("Music File");
            setSize(300, 400);
            JPanel jp1 = new JPanel();
            JPanel jp2 = new JPanel();
            JButton s= new JButton("STOP");
            JButton p= new JButton("PLAY");
            JLabel j1 = new JLabel("MusicFile");
            String[] musicfiles={"file:///home/swathi/Desktop/spot3.mp3","anitha.mp3"};
            JComboBox musiclist=new JComboBox(musicfiles);
            musiclist.setSelectedIndex(1);
            jp1.add(j1);
            jp1.add(musiclist);
            jp2.add(s);
            jp2.add(p);
            JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT,
                    true, jp1, jp2);
            splitPane.setOneTouchExpandable(true);
            getContentPane().add(splitPane);
        public static void main(String[] args) {
          AudioFile sp = new AudioFile();
            sp.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            sp.setVisible(true);
    }

  • Getting a JFrame to display  from a JSP, remaining JSP code waits for frame

    Hello,
    I'm new to Java and just started using JSPs. My objective is to call a display window (from a JSP) that shows the user a list of project selections. Once the user has made their selections and clicked a Submit button, the display class captures the selected projects to the request object as an attribute and then closes the window. The next command in the jsp then forwards the request attribute to a controller. I'm having trouble getting the display window to show-the JSP seems to hang and then timeout. Is there code I'm missing to get the JSP to stop processing while it waits for the choices to be made in the JFrame?
    Below is the JSP code and the class I'm calling. I'm seeing all my debug System.out statements but no JFrame pops up. In the JFrame class, the line f.addWindowListener(... does the capture of user selections to the request attribute.
    Any help will be greatly appreciated!!
    JSP:
    <%@ page language="java" contentType="text/html;charset=UTF-8" import="com.plumtree.remote.portlet.*,edu.app.projects.*" %>
    <%
        request.setAttribute("action", "prefDisplay");
        request.setAttribute("orderby", "title");
        ServletContext jc = getServletContext();
        DualListBox dual = new DualListBox(request,(String)jc.getAttribute("db.driver"), (String)jc.getAttribute("db.connectionstring"),"title");
         JFrame f = dual.getFrame();
         f.setVisible(true);//expect code to stop here and display frame, waiting for the user to finish.
            //Debug code that tests if frame is visible at this point -came true though did not see Jframe displayed
         if(f.isShowing()){
         System.out.println("Jframe visible");}
           //Send to ProjectsController
          request.getRequestDispatcher("pc").forward(request, response);%>               ---------------------------------------------------------------------------------------------
    JFrame Class (below)
    -Sets up Frame and corresponding Dialog box
    -Populates Dialog box with options from a database call (for user selection)
    -Should wait for user input - Window close or Submit! to capture selection and dispose of Jframe
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.EventQueue;
    import java.awt.Frame;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.WindowEvent;
    import java.lang.reflect.InvocationTargetException;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Collection;
    import java.util.Iterator;
    import java.util.SortedSet;
    import java.util.TreeSet;
    import javax.servlet.http.HttpServletRequest;
    import javax.swing.AbstractListModel;
    import javax.swing.BorderFactory;
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JList;
    import javax.swing.JPanel;
    import javax.swing.JScrollPane;
    import javax.swing.ListCellRenderer;
    import javax.swing.ListModel;
    public class DualListBox extends JPanel {
      private static final long serialVersionUID = 1L;
      private static final Insets EMPTY_INSETS = new Insets(0, 0, 0, 0);
      private static final String ADD_BUTTON_LABEL = "Add >>";
      private static final String REMOVE_BUTTON_LABEL = "<< Remove";
      private static final String DONE_BUTTON_LABEL = "Submit!";
      private static final String DEFAULT_SOURCE_CHOICE_LABEL = "Available Projects";
      private static final String DEFAULT_DEST_CHOICE_LABEL = "Your Selections";
      private String orderby, mydriver, connectionString;
      private JLabel sourceLabel;
      private JList sourceList;
      private SortedListModel sourceListModel;
      private JList destList;
      private String chosenprojects;
      private SortedListModel destListModel;
      private JLabel destLabel;
      private JButton addButton;
      private JButton removeButton;
      private JButton doneButton;
      private DatabaseHelper dh;
      protected HttpServletRequest request;
      protected JFrame f;
      protected JDialog jd;
      public DualListBox(HttpServletRequest req, String driver, String connection, String ordering) {
         System.out.println("In DualList Setup");
        request =req;
         orderby =ordering;
         connectionString = connection;
         mydriver = driver;
         f = new JFrame("Projects List Selector");     
         jd =new JDialog(f,true);
         jd.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
         System.out.println("B4 initscreen");
        initScreen();
        System.out.println("After initscreen");
        String[] DBprojects = this.dbCall();
        System.out.println("After DB Call");
        this.addSourceElements( DBprojects );   
        System.out.println("Filled screen");
        jd.getContentPane().add(this, BorderLayout.CENTER);
        //f.getContentPane().add(jd, BorderLayout.CENTER);
        jd.setSize(800, 600);
        System.out.println("OK2");
        jd.setVisible(true);
        System.out.println("OK3");
        Runnable runner = new FrameShower(jd);
        EventQueue.invokeLater(runner);
      public String getSourceChoicesTitle() {
        return sourceLabel.getText();
      public String chosenprojects() {
             return chosenprojects;
      public JFrame getFrame() {
             return f;
      public void setSourceChoicesTitle(String newValue) {
        sourceLabel.setText(newValue);
      public String getDestinationChoicesTitle() {
        return destLabel.getText();
      public void setDestinationChoicesTitle(String newValue) {
        destLabel.setText(newValue);
      public void clearSourceListModel() {
        sourceListModel.clear();
      public void clearDestinationListModel() {
        destListModel.clear();
      public void addSourceElements(ListModel newValue) {
        fillListModel(sourceListModel, newValue);
      public void setSourceElements(ListModel newValue) {
        clearSourceListModel();
        addSourceElements(newValue);
      public void addDestinationElements(ListModel newValue) {
        fillListModel(destListModel, newValue);
      private String[] dbCall(){
             if(dh==null)
                  dh = new DatabaseHelper(mydriver, connectionString);
              PreparedStatement ps = null;
              ResultSet rs = null;
              ArrayList<String>children = new ArrayList<String>();
              ArrayList<String[]>tree =new ArrayList<String[]>();
              if(orderby==null || orderby.equals("")){
                   orderby ="region";
              String query = "select title,id from projects";// order by " + orderby;
              System.out.println(query);
              try {
                   Connection conn =dh.getConnection();
                   ps = conn.prepareStatement(query);
                   rs = ps.executeQuery();
                   while (rs.next()) {
                        children.add(new String(rs.getString(1)));
                        System.out.println(rs.getString(1));
                        tree.add(new String[]{rs.getString(1),rs.getString(2)});
                   request.setAttribute("ResultTree",tree);
                   return (String[])children.toArray(new String[children.size()]);
              } catch (SQLException e) {
                   throw new RuntimeException(e);
              } finally {
                   try {
                        if (null != rs) rs.close();
                   } catch (SQLException e) {
                   try {
                        if (null != ps) ps.close();
                   } catch (SQLException e) {
      private void fillListModel(SortedListModel model, ListModel newValues) {
        int size = newValues.getSize();
        for (int i = 0; i < size; i++) {
          model.add(newValues.getElementAt(i));
      public void addSourceElements(Object newValue[]) {
        fillListModel(sourceListModel, newValue);
      public void setSourceElements(Object newValue[]) {
        clearSourceListModel();
        addSourceElements(newValue);
      public void addDestinationElements(Object newValue[]) {
        fillListModel(destListModel, newValue);
      private void fillListModel(SortedListModel model, Object newValues[]) {
        model.addAll(newValues);
      public Iterator sourceIterator() {
        return sourceListModel.iterator();
      public Iterator destinationIterator() {
        return destListModel.iterator();
      public void setSourceCellRenderer(ListCellRenderer newValue) {
        sourceList.setCellRenderer(newValue);
      public ListCellRenderer getSourceCellRenderer() {
        return sourceList.getCellRenderer();
      public void setDestinationCellRenderer(ListCellRenderer newValue) {
        destList.setCellRenderer(newValue);
      public ListCellRenderer getDestinationCellRenderer() {
        return destList.getCellRenderer();
      public void setVisibleRowCount(int newValue) {
        sourceList.setVisibleRowCount(newValue);
        destList.setVisibleRowCount(newValue);
      public int getVisibleRowCount() {
        return sourceList.getVisibleRowCount();
      public void setSelectionBackground(Color newValue) {
        sourceList.setSelectionBackground(newValue);
        destList.setSelectionBackground(newValue);
      public Color getSelectionBackground() {
        return sourceList.getSelectionBackground();
      public void setSelectionForeground(Color newValue) {
        sourceList.setSelectionForeground(newValue);
        destList.setSelectionForeground(newValue);
      public Color getSelectionForeground() {
        return sourceList.getSelectionForeground();
      public String getProjects(){
           return chosenprojects;
      private void clearSourceSelected() {
        Object selected[] = sourceList.getSelectedValues();
        for (int i = selected.length - 1; i >= 0; --i) {
          sourceListModel.removeElement(selected);
    sourceList.getSelectionModel().clearSelection();
    private void clearDestinationSelected() {
    Object selected[] = destList.getSelectedValues();
    for (int i = selected.length - 1; i >= 0; --i) {
    destListModel.removeElement(selected[i]);
    destList.getSelectionModel().clearSelection();
    private void initScreen() {
    setBorder(BorderFactory.createEtchedBorder());
    setLayout(new GridBagLayout());
    sourceLabel = new JLabel(DEFAULT_SOURCE_CHOICE_LABEL);
    sourceListModel = new SortedListModel();
    sourceList = new JList(sourceListModel);
    add(sourceLabel, new GridBagConstraints(0, 0, 1, 1, 0, 0,
    GridBagConstraints.CENTER, GridBagConstraints.NONE,
    EMPTY_INSETS, 0, 0));
    add(new JScrollPane(sourceList), new GridBagConstraints(0, 1, 1, 5, .5,
    1, GridBagConstraints.CENTER, GridBagConstraints.BOTH,
    EMPTY_INSETS, 0, 0));
    addButton = new JButton(ADD_BUTTON_LABEL);
    add(addButton, new GridBagConstraints(1, 2, 1, 2, 0, .25,
    GridBagConstraints.CENTER, GridBagConstraints.NONE,
    EMPTY_INSETS, 0, 0));
    addButton.addActionListener(new AddListener());
    removeButton = new JButton(REMOVE_BUTTON_LABEL);
    add(removeButton, new GridBagConstraints(1, 4, 1, 2, 0, .25,
    GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(
    0, 5, 0, 5), 0, 0));
    removeButton.addActionListener(new RemoveListener());
    doneButton = new JButton(DONE_BUTTON_LABEL);
    add(doneButton, new GridBagConstraints(1, 6, 1, 2, 0, .25,
    GridBagConstraints.CENTER, GridBagConstraints.NONE, new Insets(
    0, 10, 0, 10), 0, 0));
    doneButton.addActionListener(new DoneListener());
    f.addWindowListener(new java.awt.event.WindowAdapter() {
         public void windowClosing(WindowEvent winEvt) {
              //could set to null here to force use of Done button only
         chosenprojects = destList.getSelectedValues().toString();
              request.setAttribute("ProjectIDs", destList.getSelectedValues().toString());
              System.exit(0);
    destLabel = new JLabel(DEFAULT_DEST_CHOICE_LABEL);
    destListModel = new SortedListModel();
    destList = new JList(destListModel);
    add(destLabel, new GridBagConstraints(2, 0, 1, 1, 0, 0,
    GridBagConstraints.CENTER, GridBagConstraints.NONE,
    EMPTY_INSETS, 0, 0));
    add(new JScrollPane(destList), new GridBagConstraints(2, 1, 1, 5, .5,
    1.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH,
    EMPTY_INSETS, 0, 0));
    private class AddListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
    Object selected[] = sourceList.getSelectedValues();
    addDestinationElements(selected);
    clearSourceSelected();
    private class RemoveListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
    Object selected[] = destList.getSelectedValues();
    addSourceElements(selected);
    clearDestinationSelected();
    private class DoneListener implements ActionListener {
         public void actionPerformed(ActionEvent e) {
         chosenprojects = destList.getSelectedValues().toString();
         request.setAttribute("ProjectIDs", destList.getSelectedValues().toString());
         System.exit(0);      
    class FrameShower implements Runnable {
         final JDialog frame;
         public FrameShower(JDialog frame) {
              this.frame = frame;
         public void run() {
              System.out.println("B4 make visible");
              frame.setVisible(true);          
         System.out.println("Made screen visible");
    class SortedListModel extends AbstractListModel {
    private static final long serialVersionUID = 8777627817685130496L;
    SortedSet model;
    public SortedListModel() {
    model = new TreeSet();
    public int getSize() {
    return model.size();
    public Object getElementAt(int index) {
    return model.toArray()[index];
    public void add(Object element) {
    if (model.add(element)) {
    fireContentsChanged(this, 0, getSize());
    public void addAll(Object elements[]) {
    Collection c = Arrays.asList(elements);
    model.addAll(c);
    fireContentsChanged(this, 0, getSize());
    public void clear() {
    model.clear();
    fireContentsChanged(this, 0, getSize());
    public boolean contains(Object element) {
    return model.contains(element);
    public Object firstElement() {
    return model.first();
    public Iterator iterator() {
    return model.iterator();
    public Object lastElement() {
    return model.last();
    public boolean removeElement(Object element) {
    boolean removed = model.remove(element);
    if (removed) {
    fireContentsChanged(this, 0, getSize());
    return removed;
    }{code}
    Edited by: redm14A on Oct 10, 2007 11:34 AM
    Edited by: redm14A on Oct 10, 2007 11:37 AM
    Edited by: redm14A on Oct 10, 2007 11:40 AM
    Edited by: redm14A on Oct 10, 2007 11:45 AM
    Edited by: redm14A on Oct 10, 2007 11:47 AM

    redm14A wrote:
    Hmm, I was trying to avoid writing an applet. Seems my only other option then is to write a JSP that returns a javascript menu populated by options from a database call. Then I'd have the user click submit to send the options to another JSP that simply sets the request attribute and forwards to the controller. Will this be a sound alternative?
    Edited by: redm14A on Oct 10, 2007 12:29 PMSounds good to me.

Maybe you are looking for

  • PI NFE com erro 92 / stack java caindo

    Amigos, A 2 meses estamos passando por um problema com o ambiente GRC PI NFE, A 1 mes atru00E1s o Stack Java estava caido e apu00F3s tentar subir via SMICM e SAPMMC, constatei que o server0 demorava mais de 50 minutos para reportar o erro e abortar o

  • How to use BAPIs for Infopackage execution : loading multiple files

    Hello I have been told that BAPIs can be used to load multiple csv files at once for which some BAPIs exists (BAPI_IPAK_CREATE_FROM_REF , BAPI_IPAK_CREATE , etc) I have users who will be dropping their standard files in a directory (this should be a

  • Data Table with DBDatasource

    Hi, I have a grid with a DT linked to it. I need to add columns to this DT with DBDatasourse is set in each column. So that, using UDO I can save the data to the Line table. Please add some sample code for this to be done Thank You

  • Cost center for equipment

    Hello every one, I need some clarification regarding cost center of technical object. In FI asset number is having one cost center while we have to put one cost center in equipment master. When i settle my order system automaticlly pick the cost cent

  • Insufficient privileges upon executing stored procedure

    Hello Gurus, i am new to plsql, working on a stored procedure. basically, trying to create a temporary table using dynamic sql .. below is my code,upon executing , i am encoutering insufficient privileges error. not sure where i am going wrong. any h