Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 581
  • Last Modified:

How to centre my JFrame in the middle of the screen

Hi all,

I need a solution that will centre my JFrame in the middle of the screen, thanks

The code:

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.*;
import java.applet.AudioClip;
import java.applet.Applet;
import java.net.URL;

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);
     public int waitTime = 65;

/*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("backgrounds/default")) //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" ) );
            clip = Applet.newAudioClip(new URL("file:" + System.getProperty("user.dir") + "/sounds/music.au"));
            appleEaten = Applet.newAudioClip(new URL("file:" + System.getProperty("user.dir") + "/sounds/apple.au"));
      }
      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);

    }

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

     public void paint( Graphics g )
    {          
            super.paint(g);
        g.drawImage(backgroundImage,0,0,null);

          //Draw green scoreboard and black rects
        g.setColor(Color.black);
        g.fillRect(1,540,598,20);
        g.fillRect(1,34,598,6);
        g.setColor(Color.white);
        g.drawRoundRect(1,0,598,32,10,10);

          //Calls Snake paint method
          if (snake != null)
             snake.draw(g);
                  
    }
   
    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 = 610 ;
  private static final int DISPLAY_H = 610 ;

  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()
  {
    setResizable( false ) ;
    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" );
             snake = new Snake(JaySnake.this, name, (soundForApple ? appleEaten : null));
          }
     });
     
    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 );
    soundMusic.setState(true);
    soundMenu.add( soundMusic );
    soundMenu.add( soundSound ) ;
    soundSound.setState(true);

     /* Listeners */
     soundMusic.addActionListener(new ActionListener(){
               public void actionPerformed(ActionEvent e)
                 {
                    try
                    {
                         JCheckBoxMenuItem source = (JCheckBoxMenuItem)(e.getSource());
                         System.out.println(source.getText());
                         if (source.getState())
                         {
                              clip.loop();
                         }
                         else
                         {
                              clip.stop();
                         }
                         
                    }
                    catch (Exception ex)
                    {
                         System.out.println(ex);
                    }
                 }
          });
         
     soundSound.addActionListener(new ActionListener(){
               public void actionPerformed(ActionEvent e)
                 {
                    try
                    {
                         JCheckBoxMenuItem source = (JCheckBoxMenuItem)(e.getSource());
                         if (source.getState())
                         {
                                   soundForApple = true;
                                   snake.setAppleSound(appleEaten);
                         }
                         else
                         {
                                   soundForApple = false;
                                   snake.setAppleSound(null);
                         }
                    }
                    catch (Exception ex)
                    {
                         System.out.println(ex);
                    }
                 }
          });
     /* /Listeners */
     
    menubar.add( helpMenu ) ;
    helpMenu.add( userInstruct );
    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(265, 540);
               
                f.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();
    }
     } ) ;

    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 playMusic()
     {
          clip.loop();
         
     }
     
  public void start()
  {
    Thread gamePlay = new Thread( game ) ;
    gamePlay.start() ;
  }
 
//**************************Main method *************************************
       public static void main(String [] arguments)
     {
         System.out.println( "Starting JaySnake........" ) ;
         final JaySnake app = new JaySnake() ;
   
         app.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent keyevent) {
                //System.out.println("Test key press >>>>>>>>>>>>>>>>>>>>>>>>>>");
                app.snake.keyPressed(keyevent);
            }
        });
         app.setSize( DISPLAY_W, DISPLAY_H ) ;
         app.setTitle( "JaySnake Game" ) ;
         app.setVisible( true ) ;
         Splash splash = new Splash(app);

         new Thread(new Runnable()
              {
                   public void run()
                   {
                           try
                           {
                             app.playMusic();
                             Thread.sleep(200);
                        }
                        catch (InterruptedException e)
                        {
                             System.out.println(e);
                        }
                   }    
              }).start();
    }

/*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 Snake snake = null;
/* The musicclip to be played.*/
  private AudioClip clip = null;
/* The sound of the applet when eaten.*/
  private AudioClip appleEaten = null;
// Indicate if we want sound for eating the apple
     private boolean soundForApple = true;
}


Could you please provide the solution and explain the code and what it does to centre the JFrame on the screen :)

pjcrooks2000
0
pjcrooks2000
Asked:
pjcrooks2000
  • 8
  • 5
  • 4
1 Solution
 
girionisCommented:
Just use the setLocation of one of the parent classes of your frame:

app.setLocation(100, 100);

Play around wit hth ecoordinates a bit until you find the location you need. They start from the top left corner of the screen, so 100, 100 will make the window start at 100 x and 100 y axis :)
0
 
pjcrooks2000Author Commented:
Girionis is there a way to do this by using screenSize ??  
0
 
girionisCommented:
Not sure. The screen size is about the size of the screen, not about the location of where the component should be drawn.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
girionisCommented:
Ok I see what you mean. Users might have different screen sizes and you want to center according to their resolution. Let me see what I can find out.
0
 
girionisCommented:
You could use that:

Dimension screen=Toolkit.getDefaultToolkit().getScreenSize();
frame.setSize((int)screen.getWidth()-50,(int)screen.getHeight()-50);
frame.setLocation((int)screen.getWidth()/2-frame.getWidth()/2,(int)screen.getHeight()/2-frame.getHeight()/2);

(from: http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_20608275.html )
0
 
pjcrooks2000Author Commented:
heh I think I will use your earlier solution app.setLocation(100, 100);

Thanks so much g
0
 
girionisCommented:
:)
0
 
pjcrooks2000Author Commented:
0
 
zzynxSoftware engineerCommented:
Hi pjcrooks2000,

I know it's a bit late but to center your JFrame on the screen you just can use:

         app.setLocationRelativeTo(null);

It works for all screen sizes and resolutions.
0
 
pjcrooks2000Author Commented:
Hehe  zzunx,

so it does thank you for that, it is better than me having to set the co ordinates manually for screen sizes.  I knew there would be a way.

Thanks for that!

why not try my other question please http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_21111604.html

I would like for you to earn some points :)
0
 
zzynxSoftware engineerCommented:
>> why not try my other question
Looks like it's already crowdy enough over there.

>> would like for you to earn some points
Well, it's always possible to reopen this question by posting a zero-point question in
http://www.experts-exchange.com/Community_Support/

Subject: Moderator Please Reopen
Body:
Please reopen this question:
http://www.experts-exchange.com/Programming/Programming_Languages/Java/Q_21111506.html

Once reopened by a moderator, you can re-close it by accepting my comment,
because it's clearly thé answer to your question.

But if you don't want to do this, no problem. I guess other Q's will come up ;°)
0
 
girionisCommented:
>Once reopened by a moderator, you can re-close it by accepting my comment,
>because it's clearly thé answer to your question.

Actually it's not *the* answer it is *an* answer.

But I wouldn't use it since it will make your game only playable on jdk1.4 and above. Earlier versions of java do not support this method.
0
 
zzynxSoftware engineerCommented:
>>it will make your game only playable on jdk1.4 and above
True, but we don't know if that's a problem for pjcrooks2000.

pjcrooks2000, forget about reopening this Q since I see girionis fears for his points.
I don't want to fight about that again with him. ;°)
The most important is that you (and now also girionis ;°) know this solution exists.
CU
0
 
girionisCommented:
> pjcrooks2000, forget about reopening this Q since I see girionis fears for his points.

Who talked about points here? It is about a solution. First you try to claim your comment as the *only* solution and now you mentioned points. What happened? You tremble as you see me approaching you at the yearly rank?
0
 
zzynxSoftware engineerCommented:
You see what I mean pjcrooks2000?

>>... claim your comment as the *only* solution
No, as *the* solution pjcrooks2000 was looking for. (hence his comment)

>> You tremble as you see me approaching you at the yearly rank?
Indeed, I tremble all over my body 24 hours a day. At night, I can't sleep anymore.
In short: my world is collapsing.
Can anybody help me please! (Or should I post a Q for that?)
0
 
girionisCommented:
I have better things to do than argue with you over the internet.
0
 
pjcrooks2000Author Commented:
Hello to all concerned, I think I will leave this question well alone as it is but thanks for all of your comments
0

Featured Post

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 8
  • 5
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now