• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 350
  • Last Modified:

Want to create a user instructions window from my JFrame menu


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
pjcrooks2000
Asked:
pjcrooks2000
  • 23
  • 8
  • 7
  • +1
2 Solutions
 
objectsCommented:
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
 
pjcrooks2000Author Commented:
Objects where should I put this in my code?  
0
 
objectsCommented:
in the menu item's action code.
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
pjcrooks2000Author Commented:
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
 
pjcrooks2000Author Commented:
I see your from good old OZ, you been watching the Olympics at all?
0
 
objectsCommented:
>          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
 
pjcrooks2000Author Commented:
how about a folder called instructions  instructions/index.html or .txt  something like that
0
 
pjcrooks2000Author Commented:
yeah its been really good, bad luck on Harrop yesterday in the Triathlon, ex Ozzy beat her so I suppose thats ok..
0
 
pjcrooks2000Author Commented:
I have been waiting for you to come on  I saw your name posted up as a highest ranker..   Well done that man!
0
 
objectsCommented:
yes that would do. then get your url using:

URL instructions = getClass().getResource("/instructions/index.html");
0
 
objectsCommented:
>  ex Ozzy beat her so I suppose thats ok..

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

0
 
pjcrooks2000Author Commented:
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
 
pjcrooks2000Author Commented:
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
 
objectsCommented:
       JFrame f = new JFrame();
          JEditorPane p = new JEditorPane("text/html", "");
          p.setEditable(false);
          URL instructions = getClass().getResource("/instructions/index.html");
          p.setPage(instructions);
0
 
pjcrooks2000Author Commented:


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
 
JavatmCommented:
Am i missing an import net or something.... ?

Yes, your missing import java.net.*;
0
 
pjcrooks2000Author Commented:
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
 
objectsCommented:
what directory is your html file in?
0
 
pjcrooks2000Author Commented:
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
 
pjcrooks2000Author Commented:
Sorry no exception... not my Exception
0
 
objectsCommented:
should be:

URL instructions = getClass().getResource("/instructions/index.html");
0
 
pjcrooks2000Author Commented:
Very Strange, it still does not work...  

It compiles ok .... Any other ideas?   Do i need to set anything for p ?
0
 
pjcrooks2000Author Commented:
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
 
pjcrooks2000Author Commented:
Time for me to go to Bed, can anyone else help with this????

0
 
JavatmCommented:
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
 
JavatmCommented:
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
 
pjcrooks2000Author Commented:
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
 
pjcrooks2000Author Commented:
Anyone???  g ?  CEHJ?  TimYates? Javatm?  lol Objects who else is about.. Please give your solutions, or is there another way to do this?  
0
 
falterCommented:
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
 
pjcrooks2000Author Commented:
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
 
JavatmCommented:
Damn I forgot to add your JEditorPane in the JFrame =-( sorry my mistake. It was actually added on mine when I compiled yours !.
0
 
JavatmCommented:
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
 
pjcrooks2000Author Commented:
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
 
JavatmCommented:
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
 
pjcrooks2000Author Commented:
ok not a problem .... :)
0
 
pjcrooks2000Author Commented:
Excellent !
0
 
pjcrooks2000Author Commented:
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
 
JavatmCommented:
> 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
 
pjcrooks2000Author Commented:
Nooooooooo thank you :)  You earn your points !

0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

  • 23
  • 8
  • 7
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now