سؤال

I am new to java and trying to create a simple game that accepts structured English commands, parses them and displays them on a grid. It is a LAN game and the commands need to be sent to the other computer to be parsed and displayed.

I have nearly finished everything and written all the parsing code, and the client/server code, however I am stuck with the GUI and its interaction with the server and the client. right now the GUI accepts a string input, and sends it with no issues, but then when I want to send a second string, the button has greyed out and I cant write anything else.

GUI Code:

public class ServerPlayergameMain extends javax.swing.JFrame implements Runnable {
private gridGenerator gg = new gridGenerator(10,10);            
public ServerPlayerParsing serverpc = new ServerPlayerParsing();
public studentServer serverSend = new studentServer();

Thread run;
public ServerPlayergameMain() {
    initComponents();
    run = new Thread(this);
    run.start();
}

public void run(){
   gg.frameGen(); 
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    command = new javax.swing.JTextField();
    jLabel1 = new javax.swing.JLabel();
    jToggleButton1 = new javax.swing.JToggleButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

    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:");

    jToggleButton1.setText("add");
    jToggleButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jToggleButton1ActionPerformed(evt);
        }
    });

    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)
                .addComponent(jLabel1)
                .addGroup(layout.createSequentialGroup()
                    .addComponent(command, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(jToggleButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addContainerGap(27, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap(180, Short.MAX_VALUE)
            .addComponent(jLabel1)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(command, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(jToggleButton1))
            .addGap(58, 58, 58))
    );

    pack();
}

private void jToggleButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                               
        serverpc.validate(command.getText());
        String commandMessage = command.getText();
        serverSend.run(commandMessage);
}                                              


// Variables declaration - do not modify                     
private javax.swing.JTextField command;
private javax.swing.JLabel jLabel1;
private javax.swing.JToggleButton jToggleButton1;
// End of variables declaration                   
}

Server Code:

import java.awt.Point;
import javax.swing.*;  
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class studentServer{
static ServerSocket serverSocket;
static Socket socket;
static PrintWriter printWriter;
static BufferedReader bufferedReader;
static Thread thread;
Console console = new Console();


public ServerPlayergameMain gm;
    public static void main(String args[]) throws Exception{
}
public void run(String commandMessage){
    while(true){
        try{
            printWriter.println(commandMessage+"\n");
            String input = bufferedReader.readLine();//reads the input from textfield
            console.readLine("Client message: "+input);//Append to TextArea
        }catch(Exception e){}
    }
}
    public void serverStartActionPerformed() {
    System.out.println("Server has started!");
    try{
        serverSocket = new ServerSocket (8888); // socket for the server
        socket = serverSocket.accept(); // waiting for socket to accept client
        JOptionPane.showMessageDialog(null, "Your opponent has connected!", "Opponent Connection!", JOptionPane.INFORMATION_MESSAGE);
        gm = new ServerPlayergameMain();
        gm.setVisible(true);
        bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream())); // reads line from input streamer
        printWriter = new PrintWriter(socket.getOutputStream(),true);
    }catch(IOException | HeadlessException e){
        System.out.println("Server not running!"); //print message if server is not running
    }

}
}

Client Code:

import java.io.*;
import java.net.*;
import javax.swing.JOptionPane;
public class StudentClient {
static Socket socket;
static PrintWriter printWriter;
static BufferedReader bufferedReader;
static Thread thread;

public ClientPlayergameMain gm;

public void Clients(String address) {
    try{
        socket=new Socket("localhost",8888);//Socket for client
        //below line reads input from InputStreamReader
        bufferedReader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
        //below line writes output to OutPutStream
        printWriter=new PrintWriter(socket.getOutputStream(),true);
        JOptionPane.showMessageDialog(null, "Connected to server successfully", "Success", JOptionPane.INFORMATION_MESSAGE);
        gm = new ClientPlayergameMain();
        gm.setVisible(true);
                    System.out.println("Connected");//debug code
    }catch(Exception e){
       JOptionPane.showMessageDialog(null, "No Connection to server", "Error", JOptionPane.ERROR_MESSAGE);
        System.out.println("Not Connected");
    }
    thread = new Thread();
    thread.start();

}
public static void run(String commandMessage){
        while(true){
            try{
                   Console console = new Console();
              printWriter.println(commandMessage);
                                String input = bufferedReader.readLine();
                System.out.println("From server:" +input);
            }catch(Exception e) {}
        }
}
}

There is some classes that I have left out like the grid generator which has no effect on the function of the server/client and how they interact.

Please could you explain what is happening with the button, and why it stops working after sending just one string, and how I can solve this.

هل كانت مفيدة؟

المحلول

Call

run = new Thread(this);
run.start();

In

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

And RUN method should be:

public void run(){
    gg.frameGen(); 
    //...
    serverpc.validate(command.getText());
    String commandMessage = command.getText();
    serverSend.run(commandMessage);

}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top