Question

I am creating a game and i have a grid that accepts movements drawn from commands in english, and it draws perfectly but everytime i draw a new movement a new grid pops up. i dont know why it happens but it doesnt affect the functionality of the game, but it just opens more and more windows.

main game class:

public class ServerPlayergameMain extends javax.swing.JFrame implements Runnable {
   public ServerPlayerParsing serverpc = new ServerPlayerParsing();
   public studentServer serverSend = new studentServer();
   Thread run;

   public ServerPlayergameMain() {
        initComponents();
        this.setTitle("[Server] Command Quest - Hesham © 2014");
    }

    public void run(){
        serverpc.validate(command.getText());
        String commandMessage = command.getText();
        serverSend.run(commandMessage);
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        command = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jList1 = new javax.swing.JList();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        command.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                commandActionPerformed(evt);
            }
        });
        command.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                commandKeyPressed(evt);
            }
        });

        jLabel1.setText("Enter your command:");

        jButton1.setText("Go!");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jList1.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane1.setViewportView(jList1);

        jButton2.setText("Save");

        jButton3.setText("Forfeit");

        jLabel2.setText("Command Queue:");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(29, 29, 29)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton3)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(0, 132, Short.MAX_VALUE))
                            .addComponent(command))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jScrollPane1)
                            .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 88, Short.MAX_VALUE)
                            .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGap(38, 38, 38))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(90, 90, 90)
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 253, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButton2)
                        .addGap(18, 18, 18)
                        .addComponent(jButton1)
                        .addGap(0, 46, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(command, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(12, 12, 12)
                        .addComponent(jButton3)))
                .addContainerGap())
        );

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



private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
     run = new Thread(this);
     run.start();
}                                        

    // Variables declaration - do not modify                     
    private javax.swing.JTextField command;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JList jList1;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration                   
}

Parsing class:

public class ServerPlayerParsing {    
ServerGridGenerator serverGrid = new ServerGridGenerator (10, 10);
public String validate(String command){
if (wordCount(command)== 3) { 
    String[] commandArray = command.split(" ");
    commandParsing(commandArray);
} else {
    System.out.println("Error! Format incorrect!");
    System.out.println("Correct format = [COMMAND 1] [COMMAND 2] [COMMAND 3]");
}
return "";
}
public  int wordCount(String command){
String[] commandCount = command.split("\\s");
return commandCount.length;
}
public  String commandParsing(String[] commandArray) {
switch (commandArray[0]) {
case "move":
secondCommand (commandArray);
break;
default: System.out.println("Error in first command!");
}        
return " ";
}
public String secondCommand (String commandArray[]) {
switch (commandArray[1]) {
case "forward":
forwardMovement(commandArray);
break;
case "backward":
backwardMovement (commandArray);
break;
case "left":
leftMovement (commandArray);
break;
case "right":
rightMovement (commandArray);
break;
default: System.out.println("Error in second command!");
} 
return " ";
}
public   String forwardMovement (String commandArray[]) {
switch (commandArray[2]) {
     case "1":
     serverGrid.serverPlayerMoveForward(1);
     break;
     case "2":
     serverGrid.serverPlayerMoveForward(2);
     break;
     default: System.out.println("Error in third command!");
    }
return " ";
}
public   String backwardMovement (String commandArray[]) {
switch (commandArray[2]) {
     case "1":
     serverGrid.serverPlayerMoveBackward(1);
     break;
     case "2":
     serverGrid.serverPlayerMoveBackward(2);
     break;
     default: System.out.println("Error in third command!");
    }
    return " ";
}
public   String leftMovement (String commandArray[]) {
switch (commandArray[2]) {
     case "1":
     serverGrid.serverPlayerMoveLeft(1);
     break;
     case "2":
     serverGrid.serverPlayerMoveLeft(2);
     break;
     default: System.out.println("Error in third command!");
    }
    return " ";
}
public   String rightMovement (String commandArray[]) {
switch (commandArray[2]) {
     case "1":
     serverGrid.serverPlayerMoveRight(1);
     break;
     case "2":
     serverGrid.serverPlayerMoveRight(2);
     break;
     default: System.out.println("Error in third command!");
    }
return " ";
}
} 

grid class:

import java.awt.Color;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.GridLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
public class ServerGridGenerator extends JFrame {
public int serverPlayerXPos = 0;
public int serverPlayerYPos = 0;
public int clientPlayerXPos = 0;
public int clientPlayerYPos = 9;
public int endXPos = 9;
public int endYPos = 5;
int row = 10;
int column = 10;
int sizeGrid = 700;
JButton[][] squareButtons = new JButton [row][column];

public ServerGridGenerator(int r, int c) {
   squareButtons = new JButton [r][c];
   Container pane = getContentPane();
   pane.setLayout(new GridLayout(r, c));
   for(int y=0; y<c; y++){
       for (int x=0; x<r; x++) {
           System.out.println("constructor called!");
           squareButtons[y][x] = new JButton("");
           squareButtons[y][x].setOpaque(true);
           squareButtons[y][x].setBackground(Color.white);
           squareButtons[y][x].setEnabled(false);
           pane.add(squareButtons[y][x]);
       }        
   }
   squareButtons[serverPlayerYPos][serverPlayerXPos].setText(" P1");
   squareButtons[clientPlayerYPos][clientPlayerXPos].setText(" P2");
   squareButtons[endYPos][endXPos].setText(" END");

   setPreferredSize(new Dimension(sizeGrid, sizeGrid));
   setLocationRelativeTo(null);
   pack();
   setVisible(true);
}

 public void serverPlayerMoveRight (int moveBy){
    for (int i=0; i<(moveBy+1); i++) {
        squareButtons[serverPlayerYPos][serverPlayerXPos].setText(" ");
        serverPlayerXPos = serverPlayerXPos + 1;
        squareButtons[serverPlayerYPos][serverPlayerXPos].setText(" P1");
        repaint();
        validate();
    }
 }
 public void serverPlayerMoveLeft (int moveBy){
    for (int i=0; i<(moveBy+1); i++) {
        squareButtons[serverPlayerYPos][serverPlayerXPos].setText(" ");
        serverPlayerXPos = serverPlayerXPos - 1;
        squareButtons[serverPlayerYPos][serverPlayerXPos].setText(" P1");
        repaint();
        validate();
    }
 }
 public void serverPlayerMoveForward (int moveBy){
    for (int i=0; i<(moveBy+1); i++) {
        squareButtons[serverPlayerYPos][serverPlayerXPos].setText(" ");
        serverPlayerYPos = serverPlayerYPos + 1;
        squareButtons[serverPlayerYPos][serverPlayerXPos].setText(" P1");
        repaint();
        validate();
    }
 }
 public void serverPlayerMoveBackward (int moveBy){
     for (int i=0; i<(moveBy+1); i++) {
        squareButtons[serverPlayerYPos][serverPlayerXPos].setText(" ");
        serverPlayerYPos = serverPlayerYPos - 1;
        squareButtons[serverPlayerYPos][serverPlayerXPos].setText(" P1");
        repaint();
        validate();
      }
 }
}

i have reduced the code, but i think the issue lies within this code. the main class calls the parser and the parser calls the grid and draws to the grid. but i think that everytime the parse is called the line ServerGridGenerator serverGrid = new ServerGridGenerator (10, 10) runs which calls the grid. i want the grid to open once, but this is not happening. could you help me resolve this issue.

Thanks for your time.

Was it helpful?

Solution

create a new method that initially calls the grid line ServerGridGenerator serverGrid = new ServerGridGenerator (10, 10) and allows you to call it from your game main class. this will generate a grid only when its called.

OTHER TIPS

Your Frame is a also a Thread. Try to decouple this. Swing is using the observer pattern. I hope don't get punished for my answer. Create the Frame separately and let the game logic only change components displayed within the frame, but not the frame itself. I had a similar issue. Swing is tricky

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top