Solved

Want to create a user instructions window from my JFrame menu

Posted on 2004-08-26
40
339 Views
Last Modified: 2010-03-31

I have a game JFrame with a menu attached to it, I want to open up a window that has User instructions on it when a menu item is clicked.   You can see from my code that I want to happen when the User clicks on the "userInstruct" menu item.

How would I do this please  ??   I can fill in the instructions for myself.   The instructions will be simple sucg as below

Move Left = Left Arrow Key
Move Right = Right Arrow Key
Move ...................
......................
.........................etc etc

The code for my Frame is here:

import java.awt.*;
import java.awt.event.*;
import java.awt.* ;
import java.awt.event.* ;
import java.awt.image.* ;
import javax.imageio.* ;
import java.io.* ;
import javax.swing.* ;
import java.util.*;


public class JaySnake extends JFrame implements ActionListener
{
  class Game extends JPanel implements Runnable
  {
    private BufferedImage backBuffer ;
    private Graphics myBackBuffer ;
   
/*The HashMap  class is roughly equivalent to Hashtable,
 *except that it is unsynchronized and permits nulls*/
    HashMap imageMap = new HashMap(4);

/*Method used to get text from background menu items and set background image from that*/
     public void setImage(String fileName) throws Exception
     {
          if (fileName.equals("default.jpg")) //Sets background to default image
          {
                      backgroundImage = ImageIO.read( new File( "backgrounds/default.jpg" ) );
         }
         else if (fileName.equals("Long grass")) //Sets background to longGrass image
         {
                    backgroundImage = ImageIO.read( new File( "backgrounds/longGrass.jpg" ) );
         }
         else if (fileName.equals("Yellow Sand"))//Sets background to sand image
         {
                   backgroundImage = ImageIO.read( new File( "backgrounds/sand.jpg" ) );
         }
         
         else if (fileName.equals("Blue Glass")) //Sets background to blueGrass image
         {
                   backgroundImage = ImageIO.read( new File( "backgrounds/blueGlass.jpg" ) );
         }
         
         else //Sets to default if none mathced
         {
                    backgroundImage = ImageIO.read( new File( "backgrounds/default.jpg" ) );
         }
     }
     
    public Game()
    {

  /******Try read in default backgroundImage file and catch any exception*/
      try //first read in default image
      {
            backgroundImage = ImageIO.read( new File( "backgrounds/default.jpg" ) );
      }
      catch( IOException e )
      {
        System.out.println(e) ;
      }
      backBuffer = new BufferedImage( DISPLAY_W, DISPLAY_H, BufferedImage.TYPE_INT_RGB ) ;
      myBackBuffer = backBuffer.getGraphics() ;

//set up the menubar
      menubar = new JMenuBar();
      setJMenuBar(menubar);

    }

    long startTime, waitTime, elapsedTime ;
    public void paintComponent( Graphics g )
    {
      g.drawImage( backBuffer, DISPLAY_X, DISPLAY_Y, null ) ;
    }

    public void run()
    {
      //     1000/25 Frames Per Second = 40millisecond delay
      int delayTime = 1000 / 25 ;

      Thread thisThread = Thread.currentThread() ;
      while( running )
      {
        startTime = System.currentTimeMillis() ;
        // render to back buffer now
        render( myBackBuffer ) ;

        repaint() ;
        //  handle frame rate
        elapsedTime = System.currentTimeMillis() - startTime ;
        waitTime = Math.max( delayTime - elapsedTime, 5 ) ;

        try
        {
          Thread.sleep( waitTime ) ;
        }
        catch( InterruptedException e )
        {}
      }
      System.out.println( "Program Exited" ) ;
    }

   
  }

  private Thread gamePlay ;
  private boolean running = true ;
  private Game game ;

  private final int DISPLAY_X ; // value assigned in constructor
  private final int DISPLAY_Y ; // value assigned in constructor

  private static final int DISPLAY_W = 600 ;
  private static final int DISPLAY_H = 600 ;

  int size, hsize = 0, score1 = 0, score2 = 0, highscore = 0 ;

  /****Creates JMenuBar */
  private JMenuBar menubar ;
  /****Creates JMenu to house items */
  private JMenu gameMenu = new JMenu( "Game" ) ;
  private JMenuItem gameStart = new JMenuItem( "Start" ) ;
  private JMenuItem gameQuit = new JMenuItem( "Quit" ) ;

  private JMenu bgMenu = new JMenu( "Backgrounds" ) ;
  private ButtonGroup bgGroup = new ButtonGroup() ;
  private JRadioButtonMenuItem bg1 = new JRadioButtonMenuItem( "Default" ) ;
  private JRadioButtonMenuItem bg2 = new JRadioButtonMenuItem( "Long grass" ) ;
  private JRadioButtonMenuItem bg3 = new JRadioButtonMenuItem( "Yellow Sand" ) ;
  private JRadioButtonMenuItem bg4 = new JRadioButtonMenuItem( "Blue Glass" ) ;

  private JMenu soundMenu = new JMenu( "Enable sounds" ) ;
  private JCheckBoxMenuItem soundMusic = new JCheckBoxMenuItem( "Music" ) ;
  private JCheckBoxMenuItem soundSound = new JCheckBoxMenuItem( "Sounds" ) ;

  private JMenu helpMenu = new JMenu( "Help" ) ;
  private JMenuItem userInstruct = new JMenuItem( "User Instructions" ) ;
  private JMenuItem helpAbout = new JMenuItem( "About" ) ;

  /******JaySnake constructor*/
  public JaySnake()
  {
    /*****Sets title for main window*/
    //setTitle("JaySnake Game");
    //getContentPane().setLayout( new BorderLayout() ) ;
    //setResizable( false ) ;
    //Causes Menu Titles to not show up when un commented
    //setIgnoreRepaint( true ) ;
    game = new Game() ;
    getContentPane().add( game, BorderLayout.CENTER ) ;
    this.setJMenuBar( menubar );

    menubar.add( gameMenu ) ;
    gameMenu.add( gameStart ) ;
     // ActionListener to quit the game when quit is clicked
    gameStart.addActionListener( new ActionListener(){  
   
             public void actionPerformed( ActionEvent e )
     {
        String name = new String();
               name = JOptionPane.showInputDialog( "Please enter your name" );    
     }
     } ) ;
     
    gameMenu.add( gameQuit ) ;

    // ActionListener to quit the game when quit is clicked
    gameQuit.addActionListener( new ActionListener(){  
   
             public void actionPerformed( ActionEvent e )
     {
        System.exit( 0 );
     }
     } ) ;  
     
                                               
/*Background selection menubar setup adding actionlisteners*/                        
    menubar.add( bgMenu ) ;
    bgMenu.add( bg1 ); bg1.addActionListener(this);
    bgMenu.add( bg2 ); bg2.addActionListener(this);
    bgMenu.add( bg3 ); bg3.addActionListener(this);
    bgMenu.add( bg4 ); bg4.addActionListener(this);
/* "bgGroup"  groups menu items for background together*/
          bgGroup.add( bg1 );      bgGroup.add( bg2 );
          bgGroup.add( bg3 );         bgGroup.add( bg4 );

/*Sounds menubar selection with actionListeners*/    
    menubar.add( soundMenu ) ;
    soundMenu.add( soundMusic );
    soundMenu.add( soundSound ) ;

    menubar.add( helpMenu ) ;
    helpMenu.add( userInstruct ); userInstruct.addActionListener(this);
    helpMenu.add( helpAbout );    
   
    helpAbout.addActionListener( new ActionListener(){  
             public void actionPerformed( ActionEvent e )
     {
                   About dlg = new About( JaySnake.this );
                   Dimension dlgSize = dlg.getPreferredSize();
                   Dimension frmSize = getSize();
                   Point loc = getLocation();
                   dlg.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y);
                   dlg.setModal(true);
                   dlg.pack();
                   dlg.show();
    }
     } ) ;

   
   
    addWindowListener( new WindowAdapter()
    {
      public void windowClosing( WindowEvent e )
      {
        dispose();
        System.exit( 0 ) ;
      }
    } ) ;

    Insets insets = getInsets() ;
    DISPLAY_X = insets.left ;
    DISPLAY_Y = insets.top ;
    resizeToInternalSize( DISPLAY_W, DISPLAY_H ) ;
  }

  public void actionPerformed(ActionEvent e)
  {
       try
     {
          JMenuItem source = (JMenuItem)(e.getSource());
          System.out.println(source.getText());
          game.setImage(source.getText());
     }
     catch (Exception ex)
     {
          System.out.println(ex);
     }
  }

  public void resizeToInternalSize( int internalWidth, int internalHeight )
  {
    Insets insets = getInsets() ;
    final int newWidth = internalWidth + insets.left + insets.right ;
    final int newHeight = internalHeight + insets.top + insets.bottom ;

    Runnable resize = new Runnable()
    {
      public void run()
      {
        setSize( newWidth, newHeight ) ;
      }
    } ;

    if( !SwingUtilities.isEventDispatchThread() )
    {
      try
      {
        SwingUtilities.invokeAndWait( resize ) ;
      }
      catch( Exception e )
      {}
    }
    else
      resize.run() ;

    validate() ;
  }

  public void start()
  {
    Thread gamePlay = new Thread( game ) ;
    gamePlay.start() ;
  }
 
//**************************Main function*************************************
  public static void main(String [] arguments)
{
    System.out.println( "Starting JaySnake........" ) ;
    JaySnake app = new JaySnake() ;
    app.setSize( DISPLAY_W, DISPLAY_H ) ;
    app.setTitle( "JaySnake Game" ) ;
    app.setVisible( true ) ;
    Splash splash = new Splash(app);
   
   
    }


/*Render method for graphics content*/
    public void render( Graphics g )
    {
     if( backgroundImage != null )
        g.drawImage( backgroundImage, 0, 0, this ) ;

/*Draw scoreboard and player details, sets color for score and player
 *fills rectangle and text white and draws another rectangle that is used
 *to highlight the playing area*/
      g.setColor( Color.black ) ;       /*sets color to black*/
      g.fillRect( 0, 0, 598, 32 ) ; /*fillsRectangle for scoreboard*/
      g.setColor( Color.white ) ;   /*sets color to white for text*/
/*Draws text and uses score variables*/
      g.drawString( "Player 1 score: " + score1, 10, 13 ) ;
      //g.drawString( "Player 2 score: " + score2, 10, 27 ) ;
      g.drawString( "High score: " + highscore, 510, 15 ) ;

     
    }

  /******declared class variables/containers*/
  private Image backgroundImage ;
  private ImageIcon icon;
 
 
}

Thanks all


0
Comment
Question by:pjcrooks2000
  • 23
  • 8
  • 7
  • +1
40 Comments
 
LVL 92

Expert Comment

by:objects
ID: 11907859
Use a JEditorPane which supports HTML for displaying your instructions.

JFrame f = new JFrame();
JEditorPane p = new JEditorPane("text/html", "");
p.setEditable(false);
p.setPage(instructions);
f.getContentPane().add(p);
f.setSize(100, 200);
f.show();

0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11907944
Objects where should I put this in my code?  
0
 
LVL 92

Expert Comment

by:objects
ID: 11907952
in the menu item's action code.
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11907979
OK I have done that I have this

helpMenu.add( userInstruct );
    helpMenu.addActionListener( new ActionListener(){  
   
             public void actionPerformed( ActionEvent e )
     {
        JFrame f = new JFrame();
            JEditorPane p = new JEditorPane("text/html", "");
            p.setEditable(false);
            p.setPage(instructions);
            f.getContentPane().add(p);
            f.setSize(100, 200);
            f.show();

     }
     } ) ;  

and I am gettin gthis error from the IDE

symbol: variable instructions
            p.setPage(instructions);
                          ^
1 error

Process completed.


Any ideas??
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11907986
I see your from good old OZ, you been watching the Olympics at all?
0
 
LVL 92

Expert Comment

by:objects
ID: 11908016
>          p.setPage(instructions);

sorry, that's intended to be the url of the file containing your instructions.
where will your instructions be stored?

> you been watching the Olympics at all?

luckily I have a TV in the office otherwise I wouldn't be getting any work done :)
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11908047
how about a folder called instructions  instructions/index.html or .txt  something like that
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11908054
yeah its been really good, bad luck on Harrop yesterday in the Triathlon, ex Ozzy beat her so I suppose thats ok..
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11908060
I have been waiting for you to come on  I saw your name posted up as a highest ranker..   Well done that man!
0
 
LVL 92

Expert Comment

by:objects
ID: 11908065
yes that would do. then get your url using:

URL instructions = getClass().getResource("/instructions/index.html");
0
 
LVL 92

Expert Comment

by:objects
ID: 11908069
>  ex Ozzy beat her so I suppose thats ok..

yeah I think we've added that one to our tally :)

0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11908074
HMmm sorry where does that fit into the scope of things, I am still somewhat of a learning only been doing java for a couple of weeks at a time.....
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11908079
They way allen came in I could have swore she had been given a lift..... caught a taxi or something and joine on the last lap :)
0
 
LVL 92

Expert Comment

by:objects
ID: 11908080
       JFrame f = new JFrame();
          JEditorPane p = new JEditorPane("text/html", "");
          p.setEditable(false);
          URL instructions = getClass().getResource("/instructions/index.html");
          p.setPage(instructions);
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11908094


1 error Objects

symbol: class URL
          URL instructions = getClass().getResource("/instructions/index.html");
          ^
1 error

Process completed.


Am i missing an import net or something.... ?
0
 
LVL 15

Expert Comment

by:Javatm
ID: 11908311
Am i missing an import net or something.... ?

Yes, your missing import java.net.*;
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11908380
Ok coolio well I fixed that, and inserted a try catch as the IDE flagged it... I now have this

helpMenu.addActionListener( new ActionListener(){  
   
             public void actionPerformed( ActionEvent e )
     {
           
//Create new Jframe to view User instructions
        JFrame f = new JFrame();
          JEditorPane p = new JEditorPane("text/html", "");
          p.setEditable(false);
          URL instructions = getClass().getResource("instructions/index.html");
          try
        {
         p.setPage(instructions);
        }
        catch( Exception ep )
        {
              System.out.println("Not Got index.html");
              }
         

     }
      } ) ;  

However my html file is not loading for some reason  

0
 
LVL 92

Expert Comment

by:objects
ID: 11908403
what directory is your html file in?
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11908415
I have my class/jave files in root no project folders and from there i have a folder called instructions and the file inside called index.html  ....

I am getting my Exception through try catch block
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11908419
Sorry no exception... not my Exception
0
 
LVL 92

Expert Comment

by:objects
ID: 11908494
should be:

URL instructions = getClass().getResource("/instructions/index.html");
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11908661
Very Strange, it still does not work...  

It compiles ok .... Any other ideas?   Do i need to set anything for p ?
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11908730
Here is my full code, I think my Actionlistener is not working for that menuitem....  I put a System.out statement in at that line   and i am getting nothing when it is clicked......

import java.awt.*;
import java.awt.event.* ;
import java.awt.image.* ;
import javax.imageio.* ;
import java.io.* ;
import javax.swing.* ;
import java.util.*;
import java.net.*;

public class JaySnake extends JFrame implements ActionListener
{
  class Game extends JPanel implements Runnable
  {
    private BufferedImage backBuffer ;
    private Graphics myBackBuffer ;
   
/*The HashMap  class is roughly equivalent to Hashtable,
 *except that it is unsynchronized and permits nulls*/
    HashMap imageMap = new HashMap(4);

/*Method used to get text from background menu items and set background image from that*/
     public void setImage(String fileName) throws Exception
     {
          if (fileName.equals("default.jpg")) //Sets background to default image
          {
                      backgroundImage = ImageIO.read( new File( "backgrounds/default.jpg" ) );
         }
         else if (fileName.equals("Long grass")) //Sets background to longGrass image
         {
                    backgroundImage = ImageIO.read( new File( "backgrounds/longGrass.jpg" ) );
         }
         else if (fileName.equals("Yellow Sand"))//Sets background to sand image
         {
                   backgroundImage = ImageIO.read( new File( "backgrounds/sand.jpg" ) );
         }
         
         else if (fileName.equals("Blue Glass")) //Sets background to blueGrass image
         {
                   backgroundImage = ImageIO.read( new File( "backgrounds/blueGlass.jpg" ) );
         }
         
         else //Sets to default if none mathced
         {
                    backgroundImage = ImageIO.read( new File( "backgrounds/default.jpg" ) );
         }
     }
     
    public Game()
    {

  /******Try read in default backgroundImage file and catch any exception*/
      try //first read in default image
      {
            backgroundImage = ImageIO.read( new File( "backgrounds/default.jpg" ) );
      }
      catch( IOException e )
      {
        System.out.println(e) ;
      }
      backBuffer = new BufferedImage( DISPLAY_W, DISPLAY_H, BufferedImage.TYPE_INT_RGB ) ;
      myBackBuffer = backBuffer.getGraphics() ;

//set up the menubar
      menubar = new JMenuBar();
      setJMenuBar(menubar);

    }

    long startTime, waitTime, elapsedTime ;
    public void paintComponent( Graphics g )
    {
      g.drawImage( backBuffer, DISPLAY_X, DISPLAY_Y, null ) ;
    }

    public void run()
    {
      //     1000/25 Frames Per Second = 40millisecond delay
      int delayTime = 1000 / 25 ;

      Thread thisThread = Thread.currentThread() ;
      while( running )
      {
        startTime = System.currentTimeMillis() ;
        // render to back buffer now
        render( myBackBuffer ) ;

        repaint() ;
        //  handle frame rate
        elapsedTime = System.currentTimeMillis() - startTime ;
        waitTime = Math.max( delayTime - elapsedTime, 5 ) ;

        try
        {
          Thread.sleep( waitTime ) ;
        }
        catch( InterruptedException e )
        {}
      }
      System.out.println( "Program Exited" ) ;
    }

   
  }

  private Thread gamePlay ;
  private boolean running = true ;
  private Game game ;

  private final int DISPLAY_X ; // value assigned in constructor
  private final int DISPLAY_Y ; // value assigned in constructor

  private static final int DISPLAY_W = 600 ;
  private static final int DISPLAY_H = 600 ;

  int size, hsize = 0, score1 = 0, score2 = 0, highscore = 0 ;

  /****Creates JMenuBar */
  private JMenuBar menubar ;
  /****Creates JMenu to house items */
  private JMenu gameMenu = new JMenu( "Game" ) ;
  private JMenuItem gameStart = new JMenuItem( "Start" ) ;
  private JMenuItem gameQuit = new JMenuItem( "Quit" ) ;

  private JMenu bgMenu = new JMenu( "Backgrounds" ) ;
  private ButtonGroup bgGroup = new ButtonGroup() ;
  private JRadioButtonMenuItem bg1 = new JRadioButtonMenuItem( "Default" ) ;
  private JRadioButtonMenuItem bg2 = new JRadioButtonMenuItem( "Long grass" ) ;
  private JRadioButtonMenuItem bg3 = new JRadioButtonMenuItem( "Yellow Sand" ) ;
  private JRadioButtonMenuItem bg4 = new JRadioButtonMenuItem( "Blue Glass" ) ;

  private JMenu soundMenu = new JMenu( "Enable sounds" ) ;
  private JCheckBoxMenuItem soundMusic = new JCheckBoxMenuItem( "Music" ) ;
  private JCheckBoxMenuItem soundSound = new JCheckBoxMenuItem( "Sounds" ) ;

  private JMenu helpMenu = new JMenu( "Help" ) ;
  private JMenuItem userInstruct = new JMenuItem( "User Instructions" ) ;
  private JMenuItem helpAbout = new JMenuItem( "About" ) ;

  /******JaySnake constructor*/
  public JaySnake()
  {
    /*****Sets title for main window*/
    //setTitle("JaySnake Game");
    //getContentPane().setLayout( new BorderLayout() ) ;
    //setResizable( false ) ;
    //Causes Menu Titles to not show up when un commented
    //setIgnoreRepaint( true ) ;
    game = new Game() ;
    getContentPane().add( game, BorderLayout.CENTER ) ;
    this.setJMenuBar( menubar );

    menubar.add( gameMenu ) ;
    gameMenu.add( gameStart ) ;
     // ActionListener to quit the game when quit is clicked
    gameStart.addActionListener( new ActionListener(){  
   
             public void actionPerformed( ActionEvent e )
     {
        String name = new String();
               name = JOptionPane.showInputDialog( "Please enter your name" );    
     }
     } ) ;
     
    gameMenu.add( gameQuit ) ;

    // ActionListener to quit the game when quit is clicked
    gameQuit.addActionListener( new ActionListener(){  
   
             public void actionPerformed( ActionEvent e )
     {
        System.exit( 0 );
     }
     } ) ;  
     
                                               
/*Background selection menubar setup adding actionlisteners*/                        
    menubar.add( bgMenu ) ;
    bgMenu.add( bg1 ); bg1.addActionListener(this);
    bgMenu.add( bg2 ); bg2.addActionListener(this);
    bgMenu.add( bg3 ); bg3.addActionListener(this);
    bgMenu.add( bg4 ); bg4.addActionListener(this);
/* "bgGroup"  groups menu items for background together*/
          bgGroup.add( bg1 );      bgGroup.add( bg2 );
          bgGroup.add( bg3 );         bgGroup.add( bg4 );

/*Sounds menubar selection with actionListeners*/    
    menubar.add( soundMenu ) ;
    soundMenu.add( soundMusic );
    soundMenu.add( soundSound ) ;

    menubar.add( helpMenu ) ;
    helpMenu.add( userInstruct );
          helpMenu.addActionListener( new ActionListener(){  
   
             public void actionPerformed( ActionEvent e )
     {
           
//Create new Jframe to view User instructions
            System.out.println("clicked");
        JFrame f = new JFrame();
          JEditorPane p = new JEditorPane("text/html", "");
          p.setEditable(false);
          URL instructions = getClass().getResource("/instructions/index.html");
          try
        {
         p.setPage(instructions);
        }
        catch( Exception ep )
        {
              System.out.println("Not Got index.html");
              }
               }
             
      } ) ;  
     
    helpMenu.add( helpAbout );    
             helpAbout.addActionListener( new ActionListener(){  
             public void actionPerformed( ActionEvent e )
     {
//Create an instance of About class window
                   About dlg = new About( JaySnake.this );
                   Dimension dlgSize = dlg.getPreferredSize();
                   Dimension frmSize = getSize();
                   Point loc = getLocation();
                   dlg.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y);
                   dlg.setModal(true);
                   dlg.pack();
                   dlg.show();
    }
     } ) ;
//JaySnake frame Window closing        
    addWindowListener( new WindowAdapter()
    {
      public void windowClosing( WindowEvent e )
      {
        dispose();
        //System.exit( 0 ) ;
      }
    } ) ;

    Insets insets = getInsets() ;
    DISPLAY_X = insets.left ;
    DISPLAY_Y = insets.top ;
    resizeToInternalSize( DISPLAY_W, DISPLAY_H ) ;
  }

  public void actionPerformed(ActionEvent e)
  {
       try
     {
          JMenuItem source = (JMenuItem)(e.getSource());
          System.out.println(source.getText());
          game.setImage(source.getText());
     }
     catch (Exception ex)
     {
          System.out.println(ex);
     }
  }

  public void resizeToInternalSize( int internalWidth, int internalHeight )
  {
    Insets insets = getInsets() ;
    final int newWidth = internalWidth + insets.left + insets.right ;
    final int newHeight = internalHeight + insets.top + insets.bottom ;

    Runnable resize = new Runnable()
    {
      public void run()
      {
        setSize( newWidth, newHeight ) ;
      }
    } ;

    if( !SwingUtilities.isEventDispatchThread() )
    {
      try
      {
        SwingUtilities.invokeAndWait( resize ) ;
      }
      catch( Exception e )
      {}
    }
    else
      resize.run() ;

    validate() ;
  }

  public void start()
  {
    Thread gamePlay = new Thread( game ) ;
    gamePlay.start() ;
  }
 
//**************************Main function*************************************
  public static void main(String [] arguments)
{
    System.out.println( "Starting JaySnake........" ) ;
    JaySnake app = new JaySnake() ;
    app.setSize( DISPLAY_W, DISPLAY_H ) ;
    app.setTitle( "JaySnake Game" ) ;
    app.setVisible( true ) ;
    Splash splash = new Splash(app);
   
   
    }


/*Render method for graphics content*/
    public void render( Graphics g )
    {
     if( backgroundImage != null )
        g.drawImage( backgroundImage, 0, 0, this ) ;

/*Draw scoreboard and player details, sets color for score and player
 *fills rectangle and text white and draws another rectangle that is used
 *to highlight the playing area*/
      g.setColor( Color.black ) ;       /*sets color to black*/
      g.fillRect( 0, 0, 598, 32 ) ; /*fillsRectangle for scoreboard*/
      g.setColor( Color.white ) ;   /*sets color to white for text*/
/*Draws text and uses score variables*/
      g.drawString( "Player 1 score: " + score1, 10, 13 ) ;
      //g.drawString( "Player 2 score: " + score2, 10, 27 ) ;
      g.drawString( "High score: " + highscore, 510, 15 ) ;

     }

  /******declared class variables/containers*/
  private Image backgroundImage ;
  private ImageIcon icon;
 
 
}

Thanks very muchly!
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11908999
Time for me to go to Bed, can anyone else help with this????

0
 
LVL 15

Expert Comment

by:Javatm
ID: 11909666
The reason why your Help Intructions does not show is because you made a listener in the menu it should be in the menuitem
w/c is userInstruct. Add this and you will see the difference :

    userInstruct.addActionListener( new ActionListener() {  
     public void actionPerformed( ActionEvent e )
     {
                 JFrame f1 = new JFrame();
                 JEditorPane t1 = new JEditorPane();

                 f1.add(t1, BorderLayout.CENTER);
                 java.net.URL helpURL =  JaySnake.class.getResource("instructions/index.html");

                 try {
                 t1.setPage(helpURL);
                 }
                 catch(IOException h) {
                 System.out.println(""+h);            
                 }

                 f1.setSize(400, 400);
                 f1.setVisible(true);
      }
    } );

That will answer your problem . . .
Friend : Javatm
0
 
LVL 15

Accepted Solution

by:
Javatm earned 425 total points
ID: 11909686
I've fixed the bug and here it is :

import java.awt.*;
import java.awt.event.* ;
import java.awt.image.* ;
import javax.imageio.* ;
import java.io.* ;
import javax.swing.* ;
import java.util.*;
import java.net.*;

public class JaySnake extends JFrame implements ActionListener
{
  class Game extends JPanel implements Runnable
  {
    private BufferedImage backBuffer ;
    private Graphics myBackBuffer ;
   
/*The HashMap  class is roughly equivalent to Hashtable,
 *except that it is unsynchronized and permits nulls*/
    HashMap imageMap = new HashMap(4);

/*Method used to get text from background menu items and set background image from that*/
     public void setImage(String fileName) throws Exception
     {
          if (fileName.equals("default.jpg")) //Sets background to default image
          {
                    backgroundImage = ImageIO.read( new File( "backgrounds/default.jpg" ) );
         }
         else if (fileName.equals("Long grass")) //Sets background to longGrass image
         {
                   backgroundImage = ImageIO.read( new File( "backgrounds/longGrass.jpg" ) );
         }
         else if (fileName.equals("Yellow Sand"))//Sets background to sand image
         {
                  backgroundImage = ImageIO.read( new File( "backgrounds/sand.jpg" ) );
         }
         
         else if (fileName.equals("Blue Glass")) //Sets background to blueGrass image
         {
                  backgroundImage = ImageIO.read( new File( "backgrounds/blueGlass.jpg" ) );
         }
         
         else //Sets to default if none mathced
         {
                   backgroundImage = ImageIO.read( new File( "backgrounds/default.jpg" ) );
         }
     }
     
    public Game()
    {

  /******Try read in default backgroundImage file and catch any exception*/
      try //first read in default image
      {
            backgroundImage = ImageIO.read( new File( "backgrounds/default.jpg" ) );
      }
      catch( IOException e )
      {
        System.out.println(e) ;
      }
      backBuffer = new BufferedImage( DISPLAY_W, DISPLAY_H, BufferedImage.TYPE_INT_RGB ) ;
      myBackBuffer = backBuffer.getGraphics() ;

//set up the menubar
      menubar = new JMenuBar();
      setJMenuBar(menubar);

    }

    long startTime, waitTime, elapsedTime ;
    public void paintComponent( Graphics g )
    {
      g.drawImage( backBuffer, DISPLAY_X, DISPLAY_Y, null ) ;
    }

    public void run()
    {
      //     1000/25 Frames Per Second = 40millisecond delay
      int delayTime = 1000 / 25 ;

      Thread thisThread = Thread.currentThread() ;
      while( running )
      {
        startTime = System.currentTimeMillis() ;
        // render to back buffer now
        render( myBackBuffer ) ;

        repaint() ;
        //  handle frame rate
        elapsedTime = System.currentTimeMillis() - startTime ;
        waitTime = Math.max( delayTime - elapsedTime, 5 ) ;

        try
        {
          Thread.sleep( waitTime ) ;
        }
        catch( InterruptedException e )
        {}
      }
      System.out.println( "Program Exited" ) ;
    }

   
  }

  private Thread gamePlay ;
  private boolean running = true ;
  private Game game ;

  private final int DISPLAY_X ; // value assigned in constructor
  private final int DISPLAY_Y ; // value assigned in constructor

  private static final int DISPLAY_W = 600 ;
  private static final int DISPLAY_H = 600 ;

  int size, hsize = 0, score1 = 0, score2 = 0, highscore = 0 ;

  /****Creates JMenuBar */
  private JMenuBar menubar ;
  /****Creates JMenu to house items */
  private JMenu gameMenu = new JMenu( "Game" ) ;
  private JMenuItem gameStart = new JMenuItem( "Start" ) ;
  private JMenuItem gameQuit = new JMenuItem( "Quit" ) ;

  private JMenu bgMenu = new JMenu( "Backgrounds" ) ;
  private ButtonGroup bgGroup = new ButtonGroup() ;
  private JRadioButtonMenuItem bg1 = new JRadioButtonMenuItem( "Default" ) ;
  private JRadioButtonMenuItem bg2 = new JRadioButtonMenuItem( "Long grass" ) ;
  private JRadioButtonMenuItem bg3 = new JRadioButtonMenuItem( "Yellow Sand" ) ;
  private JRadioButtonMenuItem bg4 = new JRadioButtonMenuItem( "Blue Glass" ) ;

  private JMenu soundMenu = new JMenu( "Enable sounds" ) ;
  private JCheckBoxMenuItem soundMusic = new JCheckBoxMenuItem( "Music" ) ;
  private JCheckBoxMenuItem soundSound = new JCheckBoxMenuItem( "Sounds" ) ;

  private JMenu helpMenu = new JMenu( "Help" ) ;
  private JMenuItem userInstruct = new JMenuItem( "User Instructions" ) ;
  private JMenuItem helpAbout = new JMenuItem( "About" ) ;

  /******JaySnake constructor*/
  public JaySnake()
  {
    /*****Sets title for main window*/
    //setTitle("JaySnake Game");
    //getContentPane().setLayout( new BorderLayout() ) ;
    //setResizable( false ) ;
    //Causes Menu Titles to not show up when un commented
    //setIgnoreRepaint( true ) ;
    game = new Game() ;
    getContentPane().add( game, BorderLayout.CENTER ) ;
    this.setJMenuBar( menubar );

    menubar.add( gameMenu ) ;
    gameMenu.add( gameStart ) ;
     // ActionListener to quit the game when quit is clicked
    gameStart.addActionListener( new ActionListener(){  
   
     public void actionPerformed( ActionEvent e )
     {
        String name = new String();
        name = JOptionPane.showInputDialog( "Please enter your name" );    
     }
     } ) ;
     
    gameMenu.add( gameQuit ) ;

    // ActionListener to quit the game when quit is clicked
    gameQuit.addActionListener( new ActionListener(){  
   
     public void actionPerformed( ActionEvent e )
     {
        System.exit( 0 );
     }
     } ) ;  
     
                                               
/*Background selection menubar setup adding actionlisteners*/                        
    menubar.add( bgMenu ) ;
    bgMenu.add( bg1 ); bg1.addActionListener(this);
    bgMenu.add( bg2 ); bg2.addActionListener(this);
    bgMenu.add( bg3 ); bg3.addActionListener(this);
    bgMenu.add( bg4 ); bg4.addActionListener(this);
/* "bgGroup"  groups menu items for background together*/
         bgGroup.add( bg1 );      bgGroup.add( bg2 );
         bgGroup.add( bg3 );        bgGroup.add( bg4 );

/*Sounds menubar selection with actionListeners*/    
    menubar.add( soundMenu ) ;
    soundMenu.add( soundMusic );
    soundMenu.add( soundSound ) ;

    menubar.add( helpMenu ) ;
    helpMenu.add( userInstruct );


/********** Here is the Additional Codes **********************/

     userInstruct.addActionListener( new ActionListener() {  
     public void actionPerformed( ActionEvent e )
     {
                 JFrame f1 = new JFrame();
                 JEditorPane t1 = new JEditorPane();

                 f1.add(t1, BorderLayout.CENTER);
                 java.net.URL helpURL =  JaySnake.class.getResource("Sample.htm");

                 try {
                 t1.setPage(helpURL);
                 }
                 catch(IOException h) {
                 System.out.println(""+h);            
                 }

                 f1.setSize(400, 400);
                 f1.setVisible(true);
      }
    } );
 
     
     helpMenu.add( helpAbout );  

 
     helpAbout.addActionListener( new ActionListener(){  
     public void actionPerformed( ActionEvent e )
     {

     //Create an instance of About class window

                   About dlg = new About( JaySnake.this );
                   Dimension dlgSize = dlg.getPreferredSize();
                   Dimension frmSize = getSize();
                   Point loc = getLocation();
                   dlg.setLocation((frmSize.width - dlgSize.width) / 2 + loc.x, (frmSize.height - dlgSize.height) / 2 + loc.y);
                   dlg.setModal(true);
                   dlg.pack();
                   dlg.show();
       }
     } ) ;


    //JaySnake frame Window closing    
   
    addWindowListener( new WindowAdapter()
    {
      public void windowClosing( WindowEvent e )
      {
        dispose();
        //System.exit( 0 ) ;
      }
    } ) ;

    Insets insets = getInsets() ;
    DISPLAY_X = insets.left ;
    DISPLAY_Y = insets.top ;
    resizeToInternalSize( DISPLAY_W, DISPLAY_H ) ;
  }

  public void actionPerformed(ActionEvent e)
  {
     try
     {
          JMenuItem source = (JMenuItem)(e.getSource());
          System.out.println(source.getText());
          game.setImage(source.getText());
     }
     catch (Exception ex)
     {
          System.out.println(ex);
     }
  }

  public void resizeToInternalSize( int internalWidth, int internalHeight )
  {
    Insets insets = getInsets() ;
    final int newWidth = internalWidth + insets.left + insets.right ;
    final int newHeight = internalHeight + insets.top + insets.bottom ;

    Runnable resize = new Runnable()
    {
      public void run()
      {
        setSize( newWidth, newHeight ) ;
      }
    } ;

    if( !SwingUtilities.isEventDispatchThread() )
    {
      try
      {
        SwingUtilities.invokeAndWait( resize ) ;
      }
      catch( Exception e )
      {}
    }
    else
      resize.run() ;

    validate() ;
  }

  public void start()
  {
    Thread gamePlay = new Thread( game ) ;
    gamePlay.start() ;
  }
 
//**************************Main function*************************************
  public static void main(String [] arguments)
   {
    System.out.println( "Starting JaySnake........" ) ;
    JaySnake app = new JaySnake() ;
    app.setSize( DISPLAY_W, DISPLAY_H ) ;
    app.setTitle( "JaySnake Game" ) ;
    app.setVisible( true ) ;
    Splash splash = new Splash(app);  
   }


/*Render method for graphics content*/
    public void render( Graphics g )
    {
     if( backgroundImage != null )
        g.drawImage( backgroundImage, 0, 0, this ) ;

/*Draw scoreboard and player details, sets color for score and player
 *fills rectangle and text white and draws another rectangle that is used
 *to highlight the playing area*/
      g.setColor( Color.black ) ;      /*sets color to black*/
      g.fillRect( 0, 0, 598, 32 ) ; /*fillsRectangle for scoreboard*/
      g.setColor( Color.white ) ;   /*sets color to white for text*/
/*Draws text and uses score variables*/
      g.drawString( "Player 1 score: " + score1, 10, 13 ) ;
      //g.drawString( "Player 2 score: " + score2, 10, 27 ) ;
      g.drawString( "High score: " + highscore, 510, 15 ) ;

     }

  /******declared class variables/containers*/
  private Image backgroundImage ;
  private ImageIcon icon;
 
}
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11911121
Javatm .... Ooooh nealry

I have a html file called "index.html"  that is located in another folder called instructions.  I have tried "/instructions/index.html " and "instructions/index.html".  I have even move the index.html file to the root folder but it does not appear.   The button is working however.  Then i tried you nec code with the calling code and frame creating by Objects and added

f.setSize(400, 400);
f.setVisible(true);

Now the window appears but it is all grey on th einside atm.....

The code for the section is

userInstruct.addActionListener( new ActionListener() {  
     public void actionPerformed( ActionEvent e )
     {                  
     System.out.println("Instructions button pressed");
              //Create new Jframe to view User instructions
        JFrame f = new JFrame();
          JEditorPane p = new JEditorPane("text/html", "");
          p.setEditable(false);
          URL instructions = getClass().getResource("instructions/index.html");
          try
        {
         p.setPage(instructions);
        }
        catch( Exception ep )
        {
             System.out.println("Not Got index.html");
             }
         
                  f.setSize(400, 400);
            f.setVisible(true);
               
     }
      } ) ;  

everything else is the same as you have above :)

Thank you very much
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11912757
Anyone???  g ?  CEHJ?  TimYates? Javatm?  lol Objects who else is about.. Please give your solutions, or is there another way to do this?  
0
 
LVL 3

Assisted Solution

by:falter
falter earned 75 total points
ID: 11913673
I 've found a little bug in the actionPerformed
here my little correction:
        userInstruct.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                System.out.println("Instructions button pressed");
                //Create new Jframe to view User instructions
                JFrame f = new JFrame();
                JEditorPane p = new JEditorPane("text/html", "");
                f.getContentPane().add(p); // was missing in the previous code snippet
                p.setEditable(false);
                URL instructions = getClass().getResource(
                        "instructions/index.html");
               
                try {
                    p.setPage(instructions);

                } catch (Exception ep) {
                    System.out.println("Not Got index.html");
                }

                f.setSize(400, 400);
               
                f.setVisible(true);

            }
        });

b.t.w.  index.html  is residing in the following directory my/default/package/instructions
assuming JaySnake belongs to package my.default.package

Hope this  helps a little bit
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11914075
falter good job, that works great.... I will give you some points for that but i must also credit the others for their efforts and it led to the solution I hope you agree...  I hope this does not offend anyone else :)

thank you all!
0
 
LVL 15

Expert Comment

by:Javatm
ID: 11917644
Damn I forgot to add your JEditorPane in the JFrame =-( sorry my mistake. It was actually added on mine when I compiled yours !.
0
 
LVL 15

Expert Comment

by:Javatm
ID: 11917691
Oops no I dont think so, my solution as I look at it at the top from :

Comment from Javatm
Date: 08/27/2004 11:39AM PHT

and

Comment from Javatm
Date: 08/27/2004 11:45AM PHT

Added the JEditorPane to the JFrame Look at it :

    userInstruct.addActionListener( new ActionListener() {  
     public void actionPerformed( ActionEvent e )
     {
               JFrame f1 = new JFrame();
               JEditorPane t1 = new JEditorPane();

               f1.add(t1, BorderLayout.CENTER);
               java.net.URL helpURL =  JaySnake.class.getResource("instructions/index.html");

               try {
               t1.setPage(helpURL);
               }
               catch(IOException h) {
               System.out.println(""+h);          
               }

               f1.setSize(400, 400);
               f1.setVisible(true);
      }
    } );

The accepted solution should be mine ?
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11918477
Hmmmmm yes Javatm I am very sorry I must have clicked on the wrong one.. I will make it up to you thank you for all your help.. Ahhhh very sorry
0
 
LVL 15

Expert Comment

by:Javatm
ID: 11919296
I've already ask this on our friend w/c is the page editor Venabili and hopefully he can adjust this, thanks for commenting back.
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11919658
ok not a problem .... :)
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11930249
Excellent !
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11930267
Javatm my friend i think fallter should get  small token for fixing the last bug I hope your ok with that

thank you, looks like your winning on the other one I have too :)
0
 
LVL 15

Expert Comment

by:Javatm
ID: 11936091
> Thank you, looks like your winning on the other one I have too :)

No !, Thank you ! w/o your question I wouldnt be able to have points, its great to have a new friend like your, thanks again !.
0
 
LVL 8

Author Comment

by:pjcrooks2000
ID: 11936313
Nooooooooo thank you :)  You earn your points !

0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Receive file in Servlet 1 36
countX 22 70
wordappend challenge 8 88
Java Message handling in Service Layer 3 39
For customizing the look of your lightweight component and making it look lucid like it was made of glass. Or: how to make your component more Apple-ish ;) This tip assumes your component to be of rectangular shape and completely opaque. (COD…
An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now