Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 13 of 13

Thread: how to open one Jframe from main method call

  1. #1
    Junior Member
    Join Date
    Sep 2013
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default how to open one Jframe from main method call

    I have downloaded a snake game project in java. Initially the project contains three java files i.e "

    Engine.java

    Snake.java

    GameBoard.java

    And Engine.java have the main() method, when i run this Engine.java class game starts running.

    And to improve the user iteractivity i have created two JFrames :"PlayGame.java", Rules.java

    Now this project having five java classes in this project-

    Engine.java(containing main() method)
    Snake.java
    GameBoard.java
    PlayGame.java(is a JFrame)
    Rules.java(is a JFrame)

    PlayGame.java have three buttons

    Play - i want when play button getclicked snake game start/run.
    Rules - when clicked Rules.java Jframe should be opened
    Exit - exits the application

    Now what i want is at first "PlayGame.java" JFrame should appear and throw this game should start i.e when i click play button game should start But problem i am facing on running theapplication 'PlayGame.java' Jframe displaying on the window but when i click 'play button' SnakeFrame appears but snake is not moving. so plz give me solution so that i can make project in running state.

    for better understandability of the prolem i am attachig some code in my question

    Main() method code:
    public static void main(String[] args)  {
    		new PlayGame().setVisible(true);
     
    		/**JFrame frame = new JFrame("SnakeGame");
    		frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
    		frame.setResizable(false);
     
    		Canvas canvas = new Canvas();
    		canvas.setBackground(Color.black);
    		canvas.setPreferredSize(new Dimension(GameBoard.MAP_SIZE * GameBoard.TILE_SIZE, GameBoard.MAP_SIZE * GameBoard.TILE_SIZE));
     
    		frame.getContentPane().add(canvas);
    		frame.pack();
    		frame.setLocationRelativeTo(null);
    		frame.setVisible(true); 
     
    		new Engine(canvas).startGame();*/
     
     
                 }

    actionPerformed() method of Play Button
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
     
                    JFrame frame = new JFrame("SnakeGame");
    		frame.setVisible(true); 
                    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    		frame.setResizable(true);
    		Canvas canvas = new Canvas();
    		canvas.setBackground(Color.black);
                    canvas.setPreferredSize(new Dimension(GameBoard.MAP_SIZE * GameBoard.TILE_SIZE, GameBoard.MAP_SIZE * GameBoard.TILE_SIZE));
     
                    frame.getContentPane().add(canvas); 
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                    new Engine(canvas).startGame();
        }

    suggest me with some solution.


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    6,114
    My Mood
    Mellow
    Thanks
    244
    Thanked 755 Times in 741 Posts

    Default Re: how to open one Jframe from main method call

    It's hard to tell what you've changed in the original game to get what you have now, therefore it is difficult to give you specific directions. What I would advise generally is to review how the game was started and animated in the original 3 files you downloaded, and move the original code as needed that created that magic into the actionPerformed() method of the "Play" JButton. The "Play" button should simply do the same as was done in the original code to start the game.

    If you can't figure it out, you'll have to post more code. When you do, just post the Engine.java original code, and we can show you how to create a "Play" button to do what that original code did on startup, if your description of what each piece of the original code did is correct.

  3. #3
    Junior Member
    Join Date
    Sep 2013
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: how to open one Jframe from main method call

    Actually i have not doe any major chage in Engine.java file.
    I just move main() method code in theactionperformed() method of play button and create an object of PlayGame.java in the main() method and set it visibility true so that when i run the project it shows PlayGame.java JFramefirst.
    Note: PlayGame.java JFrame is created in netbeans using new->jFrame.
    For the better understanding i attach both Engine.java class and PlayGame.java JFrame in my question

    --- Update ---

    Engine.java class
    package org.psnbtech;

    import java.awt.Canvas;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import javax.swing.JFrame;
    import org.psnbtech.GameBoard.TileType;
    import org.psnbtech.Snake.Direction;


    public class Engine extends KeyAdapter {

    private static final int UPDATES_PER_SECOND = 15;

    private static final Font FONT_SMALL = new Font("Arial", Font.BOLD, 20);

    private static final Font FONT_LARGE = new Font("Arial", Font.BOLD, 40);

    public Canvas canvas;

    public GameBoard board;

    public Snake snake;

    public int score;

    public boolean gameOver;


    public Engine(Canvas canvas) {
    this.canvas = canvas;
    this.board = new GameBoard();
    this.snake = new Snake(board);

    resetGame();

    canvas.addKeyListener(this);
    //new Engine(canvas).startGame();
    }


    public void startGame() {
    canvas.createBufferStrategy(2);

    Graphics2D g = (Graphics2D)canvas.getBufferStrategy().getDrawGrap hics();
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING , RenderingHints.VALUE_ANTIALIAS_ON);

    long start = 0L;
    long sleepDuration = 0L;
    while(true) {
    start = System.currentTimeMillis();

    update();
    render(g);

    canvas.getBufferStrategy().show();

    g.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());

    sleepDuration = (1500L / UPDATES_PER_SECOND) - (System.currentTimeMillis() - start);

    if(sleepDuration > 0) {
    try {
    Thread.sleep(sleepDuration);
    } catch(Exception e) {
    e.printStackTrace();
    }
    }
    }
    }

    public void update() {
    if(gameOver || !canvas.isFocusOwner()) {
    return;
    }
    TileType snakeTile = snake.updateSnake();
    if(snakeTile == null || snakeTile.equals(TileType.SNAKE)) {
    gameOver = true;
    } else if(snakeTile.equals(TileType.FRUIT)) {
    score += 10;
    spawnFruit();
    }
    }

    public void render(Graphics2D g) {
    board.draw(g);

    g.setColor(Color.WHITE);

    if(gameOver) {
    g.setFont(FONT_LARGE);
    String message = new String("Your Score: " + score);
    g.drawString(message, canvas.getWidth() / 2 - (g.getFontMetrics().stringWidth(message) / 2), 250);

    g.setFont(FONT_SMALL);
    message = new String("Press Enter to Restart the Game");
    g.drawString(message, canvas.getWidth() / 2 - (g.getFontMetrics().stringWidth(message) / 2), 350);
    } else {
    g.setFont(FONT_SMALL);
    g.drawString("Score:" + score, 10, 20);
    }
    }

    public void resetGame() {
    board.resetBoard();
    snake.resetSnake();
    score = 0;
    gameOver = false;
    spawnFruit();
    }

    public void spawnFruit() {
    int random = (int)(Math.random() * ((GameBoard.MAP_SIZE * GameBoard.MAP_SIZE) - snake.getSnakeLength())); // if '*' replace by '/' then only one fruit is there for snake

    int emptyFound = 0;
    int index = 0;
    while(emptyFound < random) {
    index++;
    if(board.getTile(index % GameBoard.MAP_SIZE, index / GameBoard.MAP_SIZE).equals(TileType.EMPTY)) { // if '/' replaced by '*' then nothing displays on the board
    emptyFound++;
    }
    }
    board.setTile(index % GameBoard.MAP_SIZE, index / GameBoard.MAP_SIZE, TileType.FRUIT); // it also show nothing when replacing '/' by '/'
    }

    @Override
    public void keyPressed(KeyEvent e) {
    if((e.getKeyCode() == KeyEvent.VK_UP)||(e.getKeyCode() == KeyEvent.VK_W)) {
    snake.setDirection(Direction.UP);
    }
    if((e.getKeyCode() == KeyEvent.VK_DOWN)||(e.getKeyCode() == KeyEvent.VK_S)) {
    snake.setDirection(Direction.DOWN);
    }
    if((e.getKeyCode() == KeyEvent.VK_LEFT)||(e.getKeyCode() == KeyEvent.VK_A)) {
    snake.setDirection(Direction.LEFT);
    }
    if((e.getKeyCode() == KeyEvent.VK_RIGHT)||(e.getKeyCode() == KeyEvent.VK_D)) {
    snake.setDirection(Direction.RIGHT);
    }
    if(e.getKeyCode() == KeyEvent.VK_ENTER && gameOver) {
    resetGame();
    }
    }

    public static void main(String[] args) {
    new PlayGame().setVisible(true);

    /**JFrame frame = new JFrame("SnakeGame");
    frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOS E);
    frame.setResizable(false);

    Canvas canvas = new Canvas();
    canvas.setBackground(Color.black);
    canvas.setPreferredSize(new Dimension(GameBoard.MAP_SIZE * GameBoard.TILE_SIZE, GameBoard.MAP_SIZE * GameBoard.TILE_SIZE));

    frame.getContentPane().add(canvas);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);

    new Engine(canvas).startGame();*/


    } }

    --- Update ---

    PlayGame.java JFrame


    package org.psnbtech;

    import java.awt.Canvas;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.event.KeyAdapter;


    import javax.swing.JFrame;


    public class PlayGame extends javax.swing.JFrame {


    public PlayGame() {

    initComponents();
    }


    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    jButton2 = new javax.swing.JButton();
    jButton3 = new javax.swing.JButton();
    jButton1 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstan ts.EXIT_ON_CLOSE);

    jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/psnbtech/GUID-4ED364DF-2D44-40F5-9F05-31D451F15EF1-low.png"))); // NOI18N
    jButton2.setText("Rules");
    jButton2.setMaximumSize(new java.awt.Dimension(89, 39));
    jButton2.setMinimumSize(new java.awt.Dimension(89, 39));
    jButton2.setPreferredSize(new java.awt.Dimension(89, 41));
    jButton2.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton2ActionPerformed(evt);
    }
    });

    jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/psnbtech/exit (1).png"))); // NOI18N
    jButton3.setText("Exit");
    jButton3.setPreferredSize(new java.awt.Dimension(89, 41));
    jButton3.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton3ActionPerformed(evt);
    }
    });

    jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/psnbtech/play.png"))); // NOI18N
    jButton1.setText("Play");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton1ActionPerformed(evt);
    }
    });

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
    jPanel1Layout.createParallelGroup(javax.swing.Grou pLayout.Alignment.LEADING)
    .addGroup(javax.swing.GroupLayout.Alignment.TRAILI NG, jPanel1Layout.createSequentialGroup()
    .addContainerGap(277, Short.MAX_VALUE)
    .addGroup(jPanel1Layout.createParallelGroup(javax. swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addContainerGap())
    .addGroup(javax.swing.GroupLayout.Alignment.TRAILI NG, jPanel1Layout.createSequentialGroup()
    .addGroup(jPanel1Layout.createParallelGroup(javax. swing.GroupLayout.Alignment.TRAILING)
    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGap(27, 27, 27))))
    );
    jPanel1Layout.setVerticalGroup(
    jPanel1Layout.createParallelGroup(javax.swing.Grou pLayout.Alignment.LEADING)
    .addGroup(javax.swing.GroupLayout.Alignment.TRAILI NG, jPanel1Layout.createSequentialGroup()
    .addGap(40, 40, 40)
    .addComponent(jButton1)
    .addGap(35, 35, 35)
    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addGap(27, 27, 27)
    .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(75, Short.MAX_VALUE))
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout .Alignment.LEADING)
    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout .Alignment.LEADING)
    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );

    pack();
    }// </editor-fold>

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
    System.exit(0);
    }

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {

    this.dispose();
    new Rules().setVisible(true);

    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

    JFrame frame = new JFrame("SnakeGame");
    frame.setVisible(true);
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_C LOSE);
    frame.setResizable(true);
    Canvas canvas = new Canvas();
    canvas.setBackground(Color.black);
    canvas.setPreferredSize(new Dimension(GameBoard.MAP_SIZE * GameBoard.TILE_SIZE, GameBoard.MAP_SIZE * GameBoard.TILE_SIZE));
    //canvas.addKeyListener((KeyListener) this);
    frame.getContentPane().add(canvas);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    new Engine(canvas).startGame();
    }


    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JPanel jPanel1;
    // End of variables declaration
    }

  4. #4
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    6,114
    My Mood
    Mellow
    Thanks
    244
    Thanked 755 Times in 741 Posts

    Default Re: how to open one Jframe from main method call

    I forgot to say, please post your code in code tags. You can learn how in the Announcements topic at the top of this sub-forum.

    It looks like you're on the right track. How is the JButton "Play" tied to the jButton1ActionPerformed() method?

  5. #5
    Junior Member
    Join Date
    Sep 2013
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: how to open one Jframe from main method call

    Actually i create JFrame using netbeans and placed button over JFrame like we do i VB.
    So jbutton1 is the reference Of JButton and i titled it as Play

    --- Update ---

    package org.psnbtech;
     
    import java.awt.Canvas;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Graphics2D;
    import java.awt.RenderingHints;
    import java.awt.event.KeyAdapter;
    import java.awt.event.KeyEvent;
    import javax.swing.JFrame;
    import org.psnbtech.GameBoard.TileType;
    import org.psnbtech.Snake.Direction;
     
     
    public class Engine extends KeyAdapter {
     
    private static final int UPDATES_PER_SECOND = 15;
     
    private static final Font FONT_SMALL = new Font("Arial", Font.BOLD, 20);
     
    private static final Font FONT_LARGE = new Font("Arial", Font.BOLD, 40);
     
    public Canvas canvas;
     
    public GameBoard board;
     
    public Snake snake;
     
    public int score;
     
    public boolean gameOver;
     
     
    public Engine(Canvas canvas) {
    this.canvas = canvas;
    this.board = new GameBoard();
    this.snake = new Snake(board);
     
    resetGame();
     
    canvas.addKeyListener(this);
    //new Engine(canvas).startGame();
    }
     
     
    public void startGame() {
    canvas.createBufferStrategy(2);
     
    Graphics2D g = (Graphics2D)canvas.getBufferStrategy().getDrawGrap hics();
    g.setRenderingHint(RenderingHints.KEY_ANTIALIASING , RenderingHints.VALUE_ANTIALIAS_ON);
     
    long start = 0L;
    long sleepDuration = 0L;
    while(true) {
    start = System.currentTimeMillis();
     
    update();
    render(g);
     
    canvas.getBufferStrategy().show();
     
    g.clearRect(0, 0, canvas.getWidth(), canvas.getHeight());
     
    sleepDuration = (1500L / UPDATES_PER_SECOND) - (System.currentTimeMillis() - start);
     
    if(sleepDuration > 0) {
    try {
    Thread.sleep(sleepDuration);
    } catch(Exception e) {
    e.printStackTrace();
    }
    }
    }
    }
     
    public void update() {
    if(gameOver || !canvas.isFocusOwner()) {
    return;
    }
    TileType snakeTile = snake.updateSnake();
    if(snakeTile == null || snakeTile.equals(TileType.SNAKE)) {
    gameOver = true;
    } else if(snakeTile.equals(TileType.FRUIT)) {
    score += 10;
    spawnFruit();
    }
    }
     
    public void render(Graphics2D g) {
    board.draw(g);
     
    g.setColor(Color.WHITE);
     
    if(gameOver) {
    g.setFont(FONT_LARGE);
    String message = new String("Your Score: " + score);
    g.drawString(message, canvas.getWidth() / 2 - (g.getFontMetrics().stringWidth(message) / 2), 250);
     
    g.setFont(FONT_SMALL);
    message = new String("Press Enter to Restart the Game");
    g.drawString(message, canvas.getWidth() / 2 - (g.getFontMetrics().stringWidth(message) / 2), 350);
    } else {
    g.setFont(FONT_SMALL);
    g.drawString("Score:" + score, 10, 20);
    }
    }
     
    public void resetGame() {
    board.resetBoard();
    snake.resetSnake();
    score = 0;
    gameOver = false;
    spawnFruit();
    }
     
    public void spawnFruit() {
    int random = (int)(Math.random() * ((GameBoard.MAP_SIZE * GameBoard.MAP_SIZE) - snake.getSnakeLength())); // if '*' replace by '/' then only one fruit is there for snake
     
    int emptyFound = 0;
    int index = 0;
    while(emptyFound < random) {
    index++;
    if(board.getTile(index % GameBoard.MAP_SIZE, index / GameBoard.MAP_SIZE).equals(TileType.EMPTY)) { // if '/' replaced by '*' then nothing displays on the board 
    emptyFound++;
    }
    }
    board.setTile(index % GameBoard.MAP_SIZE, index / GameBoard.MAP_SIZE, TileType.FRUIT); // it also show nothing when replacing '/' by '/' 
    }
     
    @Override
    public void keyPressed(KeyEvent e) {
    if((e.getKeyCode() == KeyEvent.VK_UP)||(e.getKeyCode() == KeyEvent.VK_W)) {
    snake.setDirection(Direction.UP);
    }
    if((e.getKeyCode() == KeyEvent.VK_DOWN)||(e.getKeyCode() == KeyEvent.VK_S)) {
    snake.setDirection(Direction.DOWN);
    }
    if((e.getKeyCode() == KeyEvent.VK_LEFT)||(e.getKeyCode() == KeyEvent.VK_A)) {
    snake.setDirection(Direction.LEFT);
    }
    if((e.getKeyCode() == KeyEvent.VK_RIGHT)||(e.getKeyCode() == KeyEvent.VK_D)) {
    snake.setDirection(Direction.RIGHT);
    }
    if(e.getKeyCode() == KeyEvent.VK_ENTER && gameOver) {
    resetGame();
    }
    }
     
    public static void main(String[] args) {
    new PlayGame().setVisible(true);
     
    /**JFrame frame = new JFrame("SnakeGame");
    frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOS E);
    frame.setResizable(false);
     
    Canvas canvas = new Canvas();
    canvas.setBackground(Color.black);
    canvas.setPreferredSize(new Dimension(GameBoard.MAP_SIZE * GameBoard.TILE_SIZE, GameBoard.MAP_SIZE * GameBoard.TILE_SIZE));
     
    frame.getContentPane().add(canvas);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true); 
     
    new Engine(canvas).startGame();*/
     
     
    } }


    --- Update ---

     
    package org.psnbtech;
     
    import java.awt.Canvas;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.event.KeyAdapter;
     
     
    import javax.swing.JFrame;
     
     
    public class PlayGame extends javax.swing.JFrame  {
     
     
       public PlayGame() {
     
            initComponents();      
        }
     
     
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {
     
            jPanel1 = new javax.swing.JPanel();
            jButton2 = new javax.swing.JButton();
            jButton3 = new javax.swing.JButton();
            jButton1 = new javax.swing.JButton();
     
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
     
            jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/psnbtech/GUID-4ED364DF-2D44-40F5-9F05-31D451F15EF1-low.png"))); // NOI18N
            jButton2.setText("Rules");
            jButton2.setMaximumSize(new java.awt.Dimension(89, 39));
            jButton2.setMinimumSize(new java.awt.Dimension(89, 39));
            jButton2.setPreferredSize(new java.awt.Dimension(89, 41));
            jButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton2ActionPerformed(evt);
                }
            });
     
            jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/psnbtech/exit (1).png"))); // NOI18N
            jButton3.setText("Exit");
            jButton3.setPreferredSize(new java.awt.Dimension(89, 41));
            jButton3.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton3ActionPerformed(evt);
                }
            });
     
            jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/psnbtech/play.png"))); // NOI18N
            jButton1.setText("Play");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });
     
            javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
            jPanel1.setLayout(jPanel1Layout);
            jPanel1Layout.setHorizontalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                    .addContainerGap(277, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addContainerGap())
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGap(27, 27, 27))))
            );
            jPanel1Layout.setVerticalGroup(
                jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                    .addGap(40, 40, 40)
                    .addComponent(jButton1)
                    .addGap(35, 35, 35)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(27, 27, 27)
                    .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(75, Short.MAX_VALUE))
            );
     
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            );
     
            pack();
        }// </editor-fold>                        
     
        private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            System.exit(0);        
        }                                        
     
        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
     
            this.dispose();
            new Rules().setVisible(true);
     
        }                                        
     
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
     
                    JFrame frame = new JFrame("SnakeGame");
    		frame.setVisible(true); 
                    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    		frame.setResizable(true);
    		Canvas canvas = new Canvas();
    		canvas.setBackground(Color.black);
                    canvas.setPreferredSize(new Dimension(GameBoard.MAP_SIZE * GameBoard.TILE_SIZE, GameBoard.MAP_SIZE * GameBoard.TILE_SIZE));
                    //canvas.addKeyListener((KeyListener) this);
                    frame.getContentPane().add(canvas); 
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                    new Engine(canvas).startGame();
        }                                        
     
     
        // Variables declaration - do not modify                     
        private javax.swing.JButton jButton1;
        private javax.swing.JButton jButton2;
        private javax.swing.JButton jButton3;
        private javax.swing.JPanel jPanel1;
        // End of variables declaration                   
    }

  6. #6
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    6,114
    My Mood
    Mellow
    Thanks
    244
    Thanked 755 Times in 741 Posts

    Default Re: how to open one Jframe from main method call

    You have more than one wrong thing going on here, and I'm not sure how many of them need to be fixed (or improved) to allow the animation to function properly.

    Critical Changes:

    You should read up on modality and the method setModalityType(). You should also note that the modality of a JFrame cannot be changed, but there are other containers (like JDialog) that can do everything a JFrame can do and even more, because the modality of a JDialog can be changed.

    As you probably know, a KeyListener only works on an object that has focus. In the current architecture of this Frankenstein application, canvas never seems to have the focus. I've spent more time than I want to already with it, and I haven't figured out why or which component has the focus. I've sunk into "don't care."

    Less Critical but Still Important:

    The use of a while( true ) loop with Thread.sleep() to do animation in a Swing application is a very poor design. That by itself creates all kinds of havoc with the painting/updating mechanisms of the Swing architecture, locking the application, causing it to be unresponsive, miss changes and updates, etc. It's ugly. The better alternative is to use a javax.swing.Timer to do animation.

    You should review and learn from the Oracle Java Lesson on custom painting.

    Swing applications should be started on the Event Dispatch Thread, or EDT. One of the best articles I've found that explains the importance of this point is here. It's a comprehensive article on Java concurrency and multi-threading, but the summary at the end finally makes my point.

    Things About the Internet Your Mother Should Tell You (but won't):

    There is a lot of crap on the Internet. The tutorial you took this code from was probably more relevant when it was written than it is now, but even the author admitted that his skills were developing, and he updated article. Readers were urged to move to the later version. You didn't take the author's advice. Even with the update, the author still used the while( true ) / Thread.sleep() animation design, and the application was not started on the EDT. Either Java or the author's skills (or both) were still developing.

    So, beware. Even the official (Oracle) Java Tutorials have mistakes and are occasionally out of date, but they are the authority on the proper use of the language. I also recognize that they don't cover all topics, and they are biased to the use of Netbeans and the GUI builder. I recommend you go to them first to see the proper way to do things and then apply that knowledge to the other tutorials you find on the Internet.

    Things Oracle Won't Tell You (but should):

    Speaking of Netbeans' GUI Builder, learn how to code graphical interfaces without it, period. It's common sense: A programmer should know how to program.

    Good luck, and keep coding!

  7. #7
    Junior Member
    Join Date
    Sep 2013
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: how to open one Jframe from main method call

    Ok .but Have u any idea why the output is hanging or what would be the reason why swing output hangs.

  8. #8
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    6,114
    My Mood
    Mellow
    Thanks
    244
    Thanked 755 Times in 741 Posts

    Default Re: how to open one Jframe from main method call

    Yes. Every item in the "Critical Changes" section is contributing, and the "Less Critical" items in the order presented might have to be addressed to achieve a smooth running and reliable program.

  9. #9
    Junior Member
    Join Date
    Sep 2013
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: how to open one Jframe from main method call

    how can i set my canvas i focus.
    or also i am thinking to chage keyListener to KeyBinding, then you can plz tell me how can i set this approach in this game project/ or i Engie.java class
    i.e how can i replace keyListener to keyBinding. what things i have to keep in mind to do so .
    what things i have to change in my class to implement this or what class i have to use/extend to achieve this.

  10. #10
    Junior Member
    Join Date
    Sep 2013
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default how to handle action events in case of more than one JFrame

    I have downloaded a snake game project from the internet, initially this project contains three java files namely

    1. Engine.java
    2. Snake.java
    3. GameBoard.java
    when i run Engine.java ,game starts running ..

    Now i have done some modification in it to improve the interactivity of the game, i.e i have added two JDialog named

    1. PlayGame.java
    2.RulesDialog.java
    PlayGame.java has three JButtons :- Play button, Rules Button , Exit

    -when play button gets clicked game should start

    -when rules button gets clicked RulesDialog.java JDialog appears and when

    -exit button gets clicked application or game should be closed.
    Action of button is set in the actionPerformed() method of individual buttons.
    Now problem i am facing is when i click Play button game window is visible on the screen but snake is not moving
    and i am not getting to point how to resolve this problem ..

    So plz help me out

  11. #11
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    6,114
    My Mood
    Mellow
    Thanks
    244
    Thanked 755 Times in 741 Posts

    Default Re: how to handle action events in case of more than one JFrame

    This is the third thread on this topic asking exactly the same question. I told you what was wrong in the first thread, and I told you what to explore in order to determine a solution. I see no evidence that you've applied any of my guidance, making any changes in a positive direction.

  12. #12
    Junior Member
    Join Date
    Sep 2013
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: how to handle action events in case of more than one JFrame

    But i am not getting how to and where to implement this modalityType in which code section of the program.

    --- Update ---

    i am sorry i post it three times , but i am ot getting to any conclusion.

  13. #13
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    6,114
    My Mood
    Mellow
    Thanks
    244
    Thanked 755 Times in 741 Posts

    Default Re: how to open one Jframe from main method call

    Your effort to apply the help you've been given is dismal, but your question is interesting and there haven't been many of those lately. The code below is to show that it can be done, and it shows how to do it, maintaining (somewhat) the structure of the code you started with. However, I have eliminated without replacement probably the most significant barrier to achieving your goal, the while( true ) loop. I suggested you replace that with a javax.swing.Timer. Have you done that yet? I'm not saying my example is perfect. Perfect takes a little longer.

    As always, keep coding, and good luck!

    Instructions: Select "Play" in the Snake Game Control interface, and then type any key when the Game window appears. Check the console output for verification that a keypress was detected.

    A class to start the game off right:
    import javax.swing.SwingUtilities;
     
    // class SNakeGame creates an instance of GameControl on the EDT which
    // presents game control panel interface
    public class SnakeGame
    {
        // the main method launches the game control panel on the EDT
        public static void main( String[] args )
        {
            SwingUtilities.invokeLater( new Runnable()
            {
                public void run()
                {
                    new GameControl();
                }
            } );
     
        } // end method main()
     
    } // end class SnakeGame
    The GameControl class that presents the interface you've tried to add:
    import java.awt.Dimension;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
     
    import javax.swing.JButton;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
     
    // class GameControl presents a JFrame
    public class GameControl
    {
        // the default constructor
        public GameControl()
        {
            // set the dialog's basic characteristics
            JFrame gameControlDialog = new JFrame();
            gameControlDialog.setTitle( "Snake Game Control" );
            gameControlDialog.setDefaultCloseOperation( JDialog.EXIT_ON_CLOSE );
            gameControlDialog.setModalExclusionType( null );
            gameControlDialog.setPreferredSize( new Dimension( 400, 65 ) );
     
            gameControlDialog.add(  GameControlButtonPanel() );
            gameControlDialog.pack();
            gameControlDialog.setVisible( true );
     
        } // end default constructor
     
     
        // method GameControlButtonPanel returns a JPanel with the buttons
        // needed to control the game
        private JPanel GameControlButtonPanel()
        {
            JButton playGame = new JButton( "Play" );
            JButton pauseGame = new JButton( "Pause" );
            JButton resetGame = new JButton( "Reset" );
            JButton quitGame = new JButton( "Quit" );
     
            playGame.addActionListener( new ActionListener()
            {
                @Override
                public void actionPerformed( ActionEvent e )
                {
                    new SnakeEngine();
     
                } // end actionPerformed() method
     
            } );
     
            pauseGame.addActionListener( new ActionListener()
            {
                @Override
                public void actionPerformed( ActionEvent e )
                {
     
     
                } // end actionPerformed() method
     
            } );
     
            resetGame.addActionListener( new ActionListener()
            {
                @Override
                public void actionPerformed( ActionEvent e )
                {
     
     
                } // end actionPerformed() method
     
            } );
     
            quitGame.addActionListener( new ActionListener()
            {
                @Override
                public void actionPerformed( ActionEvent e )
                {
     
     
                } // end actionPerformed() method
     
            } );
     
            JPanel gameButtonPanel = new JPanel();
     
            gameButtonPanel.add( playGame );
            gameButtonPanel.add( pauseGame );
            gameButtonPanel.add( resetGame );
            gameButtonPanel.add( quitGame );
     
            return gameButtonPanel;
     
        } // end method GameControlButtonPanel()
     
    } // end class GameControl
    A collection of the classes from the tutorial you followed, modified:
    import java.awt.Color;
    import java.awt.Dialog;
    import java.awt.Dimension;
    import java.awt.Font;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.Point;
    import java.awt.event.KeyEvent;
    import java.awt.event.KeyListener;
    import java.util.LinkedList;
     
    import javax.swing.JDialog;
    import javax.swing.JPanel;
     
    public class SnakeEngine implements KeyListener
    {
        private static final int UPDATES_PER_SECOND = 10;
        private static final Font FONT_SMALL = new Font("Times New Roman",
                Font.BOLD, 20);
        private static final Font FONT_LARGE = new Font("Times New Roman",
                Font.BOLD, 40);
        private JDialog snakeDialog;
        private DrawPanel panel;
        private SnakeBoard board;
        private SnakeContents snake;
        private int score;
        private boolean gameOver;
     
        public SnakeEngine()
        {
            this.board = new SnakeBoard();
            this.snake = new SnakeContents( board );
     
            snakeDialog = new JDialog();
            snakeDialog.setTitle( "Snake Game" );
     
            snakeDialog.setModalityType( Dialog.ModalityType.MODELESS );
            snakeDialog.setDefaultCloseOperation( JDialog.DISPOSE_ON_CLOSE );
            snakeDialog.setResizable( false );
     
            this.panel = new DrawPanel();
            panel.setBackground(Color.BLACK);
            panel.setPreferredSize(new Dimension(SnakeBoard.MAP_SIZE * 
                    SnakeBoard.TILE_SIZE, SnakeBoard.MAP_SIZE * SnakeBoard.TILE_SIZE));
     
            snakeDialog.add(panel);
     
            snakeDialog.pack();
            snakeDialog.setLocationRelativeTo(null);
     
            resetGame();
     
            panel.addKeyListener(this);
            System.out.println( "Panel is focusable = " + panel.isFocusable() );
     
            panel.requestFocus();
     
            update();
     
            snakeDialog.setVisible( true );
        }
     
        private void update() {
            if( gameOver || !panel.hasFocus() )
            {
                System.out.println( "Returning" );
                return;
            }
            SnakeBoard.TileType snakeTile = snake.updateSnake();
            if(snakeTile == null || snakeTile.equals(SnakeBoard.TileType.SNAKE)) {
                gameOver = true;
            } else if(snakeTile.equals(SnakeBoard.TileType.FRUIT)) {
                score += 10;
                spawnFruit();
            }
        }
     
        private void resetGame() {
            board.resetBoard();
            snake.resetSnake();
            score = 0;
            gameOver = false;
            spawnFruit();
        }
     
        private void spawnFruit() {
            int random = (int)(Math.random() * ((SnakeBoard.MAP_SIZE * 
                    SnakeBoard.MAP_SIZE) - snake.getSnakeLength()));
     
            int emptyFound = 0;
            int index = 0;
            while(emptyFound < random) {
                index++;
                if(board.getTile(index % SnakeBoard.MAP_SIZE, index / 
                        SnakeBoard.MAP_SIZE).equals(SnakeBoard.TileType.EMPTY))
                {
                    emptyFound++;
                }
            }
            board.setTile(index % SnakeBoard.MAP_SIZE, index / 
                    SnakeBoard.MAP_SIZE, SnakeBoard.TileType.FRUIT);
        }
     
        @Override
        public void keyPressed(KeyEvent e)
        {
            System.out.println( "A key was pressed." );
        }
     
        class DrawPanel extends JPanel
        {
     
            public void paintComponent( Graphics g )
            {
                super.paintComponent( g );
     
                g.setColor(Color.WHITE);
     
                if(gameOver) {
                    g.setFont(FONT_LARGE);
                    String message = new String("Final Score: " + score);
                    g.drawString(message, panel.getWidth() / 2 - 
                            (g.getFontMetrics().stringWidth(message) / 2), 250);
     
                    g.setFont(FONT_SMALL);
                    message = new String("Press Enter to Restart");
                    g.drawString(message, panel.getWidth() / 2 - 
                            (g.getFontMetrics().stringWidth(message) / 2), 350);
                } else {
                    g.setFont(FONT_SMALL);
                    g.drawString("Score:" + score, 10, 20);
                }
            }
     
        } // end class DrawPanel
     
        @Override
        public void keyTyped( KeyEvent e )
        {
            // end method 
        }
     
        @Override
        public void keyReleased( KeyEvent e )
        {
            // end method 
        }
     
    }
     
    class SnakeContents
    {
        public static enum Direction
        {
            UP,
            DOWN,
            LEFT,
            RIGHT,
            NONE
        }
     
        private Direction currentDirection;
     
        private Direction temporaryDirection;
     
        private SnakeBoard board;
     
        private LinkedList<Point> points;
     
        public SnakeContents(SnakeBoard board) {
            this.board = board;
            this.points = new LinkedList<Point>();
        }
     
        public void resetSnake() {      
            this.currentDirection = Direction.NONE;
            this.temporaryDirection = Direction.NONE;
     
            Point head = new Point(SnakeBoard.MAP_SIZE / 2, SnakeBoard.MAP_SIZE / 2);
            points.clear();
            points.add(head);
            board.setTile(head.x, head.y, SnakeBoard.TileType.SNAKE);      
        }
     
        public void setDirection(Direction direction) {
            if(direction.equals(Direction.UP) && currentDirection.equals(Direction.DOWN)) {
                return;
            } else if(direction.equals(Direction.DOWN) && currentDirection.equals(Direction.UP)) {
                return;
            } else if(direction.equals(Direction.LEFT) && currentDirection.equals(Direction.RIGHT)) {
                return;
            } else if(direction.equals(Direction.RIGHT) && currentDirection.equals(Direction.LEFT)) {
                return;
            }
            this.temporaryDirection = direction;
        }
     
        public SnakeBoard.TileType updateSnake() {
            this.currentDirection = temporaryDirection;
     
            Point head = points.getFirst(); 
     
            switch(currentDirection) {
     
                case UP:
                    if(head.y <= 0) {
                        return null;
                    }
                    points.push(new Point(head.x, head.y - 1));
                    break;
     
                case DOWN:
                    if(head.y >= SnakeBoard.MAP_SIZE - 1) {
                        return null;
                    }
                    points.push(new Point(head.x, head.y + 1));
                    break;
     
                case LEFT:
                    if(head.x <= 0) {
                        return null;
                    }
                    points.push(new Point(head.x - 1, head.y));
                    break;
     
                case RIGHT:
                    if(head.x >= SnakeBoard.MAP_SIZE - 1) {
                        return null;
                    }
                    points.push(new Point(head.x + 1, head.y));
                    break;
     
                case NONE:
                    return SnakeBoard.TileType.EMPTY;
            }
     
            head = points.getFirst();
     
            SnakeBoard.TileType oldType = board.getTile(head.x, head.y);
            if(!oldType.equals(SnakeBoard.TileType.FRUIT)) {
                Point last = points.removeLast();
                board.setTile(last.x, last.y, SnakeBoard.TileType.EMPTY);
                oldType = board.getTile(head.x, head.y);
            }
     
            board.setTile(head.x, head.y, SnakeBoard.TileType.SNAKE);
     
            return oldType;
        }
     
        public int getSnakeLength() {
            return points.size();
        }
     
        public Direction getCurrentDirection() {
            return currentDirection;
        }
     
    }
     
    class SnakeBoard
    {
        public static final int TILE_SIZE = 25;
     
        public static final int MAP_SIZE = 20;
     
        public static enum TileType {
     
            SNAKE(Color.GREEN),
     
            FRUIT(Color.RED),
     
            EMPTY(null);
     
            private Color tileColor;
     
            private TileType(Color color) {
                this.tileColor = color;
            }
     
            public Color getColor() {
                return tileColor;
            }
     
        }
     
        private TileType[] tiles;
     
        public SnakeBoard() {
            tiles = new TileType[MAP_SIZE * MAP_SIZE];
        }
     
        public void resetBoard() {
            for(int i = 0; i < tiles.length; i++) {
                tiles[i] = TileType.EMPTY;
            }
        }
     
        public void setTile(int x, int y, TileType type) {
            tiles[y * MAP_SIZE + x] = type;
        }
     
        public TileType getTile(int x, int y) {
            return tiles[y * MAP_SIZE + x];
        }
     
        public void draw(Graphics2D g) {
            g.setColor(TileType.SNAKE.getColor());
     
            for(int i = 0; i < tiles.length; i++) {
                int x = i % MAP_SIZE;
                int y = i / MAP_SIZE;
     
                if(tiles[i].equals(TileType.EMPTY)) {
                    continue;
                }
     
                if(tiles[i].equals(TileType.FRUIT)) {
                    g.setColor(TileType.FRUIT.getColor());
                    g.fillOval(x * TILE_SIZE + 4, y * TILE_SIZE + 4, TILE_SIZE - 8, TILE_SIZE - 8);
                    g.setColor(TileType.SNAKE.getColor());
                } else {
                    g.fillRect(x * TILE_SIZE + 1, y * TILE_SIZE + 1, TILE_SIZE - 2, TILE_SIZE - 2);
                }
            }
        }
     
    }

Similar Threads

  1. Replies: 2
    Last Post: November 18th, 2012, 02:09 PM
  2. Why cant I call on the array I returned in the main method?
    By ColeTrain in forum What's Wrong With My Code?
    Replies: 3
    Last Post: November 16th, 2012, 04:08 PM
  3. How to call a value from a different method to main
    By CrimsonFlash in forum What's Wrong With My Code?
    Replies: 13
    Last Post: October 22nd, 2011, 07:29 PM
  4. How do I call a method from the main method?
    By JavaStudent1988 in forum Java Theory & Questions
    Replies: 5
    Last Post: October 19th, 2011, 09:37 PM
  5. Open JFrame Form With Button
    By cardamis in forum AWT / Java Swing
    Replies: 2
    Last Post: April 12th, 2011, 04:18 AM

Tags for this Thread