Solved

JApplet won't run, Server works, Client can't execute, no errors, doesn't show up in browser

Posted on 2004-04-16
16
528 Views
Last Modified: 2010-05-18
I have an HTML file with following code:
<HTML>
<HEAD>
<TITLE> A Simple Program </TITLE>
</HEAD>
<BODY>
<APPLET CODE="SchifferlVersenkenClient.class" WIDTH=150 HEIGHT=250>
</APPLET>
</BODY>
</HTML>







My Server works, is a JFrame, Code:
//Java core packages
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;

//Java extension packages
import javax.swing.*;

public class SchifferlVersenkenServer extends JFrame {
    private byte board[];
    private JTextArea outputArea;
    public Player players[];
    private ServerSocket server;
    private int currentPlayer;
   
    //set up SchifferlVersenken server and GUI that displays messages
    public SchifferlVersenkenServer()
    {
        super( "SchifferlVersenkenServer" );
       
        board = new byte [ 121 ];
        players = new Player[ 2 ];
        currentPlayer = 0;
       
        //set up ServerSocket
        try {
            server = new ServerSocket( 5001, 2 );
        }
        //process porblems creating ServerSocket
        catch( IOException ioException ) {
            ioException.printStackTrace();
            System.exit( 1 );
        }
       
        //set up JTextArea to display messages during execution
        outputArea = new JTextArea();
        getContentPane().add( outputArea, BorderLayout.CENTER );
        outputArea.setText( "Server awaiting connections\n" );
       
        setSize( 300, 300 );
        setVisible( true );
    }
   
    //wait for two connections so game can be played
    public void execute()
    {
        //wait for each client to connect
        for ( int i = 0; i < players.length; i ++ ) {
           
            //wait for connection, crate Player, start thread
            try {
                players[ i ] = new Player( server.accept(), i );
                players[ i ].start();
            }
           
            //process problems receiving connection from client
            catch( IOException ioException ) {
                ioException.printStackTrace();
                System.exit( 1 );
            }
        }
   
       
        //Player X is suspended until Player 0 connects.
        //Resume player X now.
        synchronized ( players[ 0 ] ) {
            players[ 0 ].setSuspended( false );
            players[ 0 ].notify();
        }
    } //end method execute
   
    //display a message in outputArea
    public void display( String message )
    {
        outputArea.append( message + "\n" );
    }
   
    //Determine if a move is valid.
    //This method is synchronized because only one move can be
    //made at a time.
    public synchronized boolean validMove(
    int location, int player )
    {
        boolean moveDone = false;
       
        //while not current player, must wait for turn
        while ( player != currentPlayer ) {
            //wait for turn
            try{
                wait();
            }
           
            //catch wait interruptions
            catch ( InterruptedException interruptedException ) {
                interruptedException.printStackTrace();
            }
        }
       
        //if location not occupied, make move
        if ( !isOccupied( location ) ) {
           
            //set move in board array
            board[ location ] =
            ( byte ) ( currentPlayer == 0 ? 'X' : 'O' );
           
            //change current player
            currentPlayer = ( currentPlayer + 1 ) % 2;
           
            //let new current player know that move occurred
            players[ currentPlayer ].otherPlayerMoved( location );
           
            //tell waiting player to continue
            notify();
           
            //tell player that made move was valid
            return true;
        }
       
        //tell player that made move was not valid
        else
            return false;
    }
   
    //determine whether location is occupied
    public boolean isOccupied( int location )
    {
        if ( board[ location ] == 'X' || board [ location ] == 'O' )
            return true;
        else
            return false;
    }
   
    //placecode in this methodto determine whether game over
    public boolean gameOver()
    {
        return false;
    }
    //execute application
    public static void main( String args[] )
    {
        SchifferlVersenkenServer application = new SchifferlVersenkenServer();
       
        application.setDefaultCloseOperation(
        JFrame.EXIT_ON_CLOSE );
       
        application.execute();
    }
   
    //private inner class player manages each player as a thread
    private class Player extends Thread {
        private Socket connection;
        private DataInputStream input;
        private DataOutputStream output;
        private int playerNumber;
        private char mark;
        protected boolean suspended = true;
       
        //set up player thread
        public Player( Socket socket, int number )
        {
            playerNumber = number;
            //specify players mark
            mark = ( playerNumber == 0 ? 'X' : 'O' );
           
            connection = socket;
           
            //obtain streams from Socket
            try {
                input = new DataInputStream(
                connection.getInputStream() );
                output = new DataOutputStream(
                connection.getOutputStream() );
            }
           
            //process problems getting streams
            catch( IOException ioException ) {
                ioException.printStackTrace();
                System.exit( 1 );
            }
        }
       
        //send message that other player moved; message contains
        //a string followed by an int
        public void otherPlayerMoved ( int location )
         {
             //send message indicating move
             try {
                 output.writeUTF( "Opponent moved" );
                 output.writeInt ( location );
             }
             
             //process problems sending message
             catch ( IOException ioException ) {
                 ioException.printStackTrace();
             }
        }
       
        //control thread's execution
        public void run()
        {
            //send client message indicationg its mark (X or O),
            //process messages from client
            try {
                display( "Player " + ( playerNumber == 0 ?
                'X' : 'O' ) + "connected" );
               
                //send player's mark
                output.writeChar( mark );
               
                //send message indicating connection
                output.writeUTF( "Player " +
                ( playerNumber == 0 ? "X connected\n" :
                    "O connected, please wait\n" ) );
                   
                    //if player X, wait for another player to arrive
                    if ( mark == 'X' ) {
                        output.writeUTF( "Waiting for another player" );
                       
                        //wait for player O
                        try {
                            synchronized( this ) {
                                while ( suspended )
                                    wait();
                            }
                        }
                       
                        //process inerruptions while waiting
                        catch ( InterruptedException exception ) {
                            exception.printStackTrace();
                        }
                       
                        //send message that other player connected and
                        //player X can make a move
                        output.writeUTF(
                        "Other player connected. Your move." );
                    }
                   
                    //while game not over
                    while ( !gameOver() ) {
                        //get move location from client
                        int location = input.readInt();
                       
                        //check for valid move
                        if ( validMove( location, playerNumber ) ) {
                            display( "loc: " + location );
                            output.writeUTF( "valid move." );

                        }
                        else
                            output.writeUTF( "Invalid move, try again" );
                    }
                   
                    //close connection to client
                    connection.close();
            }
           
            //process problems communicating with client
            catch ( IOException ioException ) {
                ioException.printStackTrace();
                System.exit( 1 );
            }
        }
       
        //set whether or not thread is suspended
        public void setSuspended( boolean status )
        {
            suspended = status;
        }
       
    } //end class Player
} //end class SchifferlVersenkenServer
       








This is the Client of the program, it has no errors, but won't show up in the browser, Code:        
//Java core packages
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;

//Java extension packages
import javax.swing.*;

//Client class to let a user play SchifferlVersenken with
//another user across a network.
public class SchifferlVersenkenClient extends JApplet
implements Runnable {
    private JTextField idField;
    private JTextArea displayArea;
    private JPanel boardPanel, panel2;
    private Square board[][], currentSquare;
    private Socket connection;
    private DataInputStream input;
    private DataOutputStream output;
    private Thread outputThread;
    private char myMark;
    private boolean myTurn;
   
    //Set up user-inferface and board
    public void init()
    {
        Container container = getContentPane();
       
        //set up JTextArea to display messages to user
        displayArea = new JTextArea( 4,30 );
        displayArea.setEditable( false );
        container.add( new JScrollPane( displayArea ),
        BorderLayout.SOUTH );
       
        //set up panel for squares in board
        boardPanel = new JPanel();
        boardPanel.setLayout( new GridLayout( 3, 3, 0, 0 ) );
       
        //create board
        board = new Square[ 3 ][ 3 ];
       
        //When creating a Square, the location argument to the
        //constructor is a value from 0 to 8 indicating th
        // position of the Square on the board. Values 0, 1
        //and 2 are the first row, values 3, 4, and 5 are the
        //second row. Values 6, 7 and 8 are the third row.
        for ( int row = 0; row < board.length; row++ ) {
            for ( int column = 0;
            column < board[ row ].length; column++ ) {
               
                //create Square
                board[ row ][ column ] =
                new Square(' ', row * 3 + column );
                           
                boardPanel.add( board[ row ][ column ] );

            }
     
        }
        //textfield to display player's mark
        idField = new JTextField();
        idField.setEditable( false );
        container.add( idField, BorderLayout.NORTH );
       
        //set up panel to contain boardPanel (for layout)
        panel2 = new JPanel();
        panel2.add( boardPanel, BorderLayout.CENTER );
        container.add( panel2, BorderLayout.CENTER );
    }
   
    //Make connection to server and get associated streams.
    //Start seperate thread to allow this applet to
    //continually update its output in text area display.
    public void start()
    {
        //connect to server, get streams and start outputThread
        try {
           
            //make connection
            connection = new Socket(
            InetAddress.getByName( "127.0.0.1" ), 5001 );
           
            //get streams
            input = new DataInputStream(
            connection.getInputStream() );
            output = new DataOutputStream(
            connection.getOutputStream() );
        }
       
        //catch problems setting up connection and streams
        catch ( IOException ioException ) {
            ioException.printStackTrace();
        }
       
        //create and start output thread
        outputThread = new Thread( this );
        outputThread.start();
    }
   
    //control thread that allows continous update of the
    //text area displayArea
   public void run()
   {
       
       //get player's mark ( X or O )
        try {
            myMark = input.readChar();
            idField.setText( "You are player \"" + myMark + "\"" );
            myTurn = ( myMark == 'X' ? true : false );
        }
       
        //process problems communicating with server
        catch ( IOException ioException ) {
            ioException.printStackTrace();
        }
     
        //receive messages sent to client and output them
        while ( true ) {
           
           //read message from server and process message
            try {
                String message = input.readUTF();
                processMessage( message );
            }
           
            //process problems communicating with server
            catch ( IOException ioException ) {
                ioException.printStackTrace();
            }
        }
    } //end method run
   
    //process messages received by client
    public void processMessage( String message )
    {
        //valid move occurred
        if ( message.equals( "Valid move." ) ) {
            displayArea.append( "Valid move, pleast wait.\n");
           
            //set mark in square from event-dispatch thread
            SwingUtilities.invokeLater(
           
            new Runnable() {
               
                public void run()
                {
                    currentSquare.setMark( myMark );
                }
            }
        ); //end call to invokeLater
    }
       
        //invalid move occurred
        else if ( message.equals( "Invalid move, try again" ) ) {
            displayArea.append( message + "\n" );
            myTurn = true;
        }
       
        //opponent moved
        else if ( message.equals( "Opponent moved" ) ) {
           
            //get move location and update board
            try {
                final int location = input.readInt();
               
                //set mark in square from event-dispatch thread
                SwingUtilities.invokeLater(
               
                new Runnable() {
                   
                    public void run()
                    {
                        int row = location / 3;
                        int column = location % 3;
                       
                        board[ row ][ column ].setMark(
                        ( myMark == 'X' ? 'O' : 'X' ) );
                        displayArea.append(
                        "Opponent moved. Your turn.\n" );
                    }
                }
               
                ); //end call to invokeLater
               
                myTurn = true;
            }
           
            //process problems communicating with server
            catch ( IOException ioException ) {
                    ioException.printStackTrace();
                }
            }
           
            //simply display message
            else
                displayArea.append( message + "\n" );
           
            displayArea.setCaretPosition(
            displayArea.getText().length() );
        } //end method processMessage
       
        //send message to server indicating clicked square
        public void sendClickedSquare( int location )
        {
            if ( myTurn ) {
               
                //send location to server
                try {
                    output.writeInt( location );
                    myTurn = false;
                }
               
                //process problems communicating with server
                catch ( IOException ioException ) {
                    ioException.printStackTrace();
                }
            }
        }
       
        //set current Square
        public void setCurrentSquare( Square square )
        {
            currentSquare = square;
        }
       
        //private class Square extends JPanel
        private class Square extends JPanel {
        private char mark;
        private int location;
       
        public Square( char squareMark, int squareLocation )
        {
            mark = squareMark;
            location = squareLocation;
       
        addMouseListener(
       
        new MouseAdapter() {
           
            public void mouseReleased( MouseEvent e )
            {
                setCurrentSquare( Square.this );
                sendClickedSquare( getSquareLocation() );
            }
        } //end anonymous inner class
     
        ); //end call to addMouseListener
    } //end Square constructor
   
    //return preferred size of Square
    public Dimension getPreferredSize()
    {
        return new Dimension( 30, 30 );
    }
   
    //return minimum size of Square
    public Dimension getMinimumSize()
    {
        return getPreferredSize();
    }
   
    //set mark for Square
    public void setMark ( char newMark )
    {
        mark = newMark;
        repaint();
    }
   
    //return Square location
    public int getSquareLocation()
    {
        return location;
    }
   
    //draw Square
    public void paintComponent( Graphics g )
    {
        super.paintComponent( g );
       
        g.drawRect( 0, 0, 29, 29 );
        g.drawString( String.valueOf( mark ),  11, 20 );
 
    }
   
} //end class Square

} //end class SchifferlVersenkenClient

0
Comment
Question by:tripsy
  • 8
  • 6
16 Comments
 
LVL 92

Expert Comment

by:objects
ID: 10847983
have u checked the java console for errors?

By the looks of it I'm guessing that it is failing to connect to the server. The default permissions for an applet only allow it to connect to the server that it was loaded from.
ie. the following should be connecting to the server the applet was loaded from instead of localhost:

           connection = new Socket(InetAddress.getByName( "127.0.0.1" ), 5001 );

maybe something like:

           connection = new Socket(getCodeBase().getHost(), 5001 );
0
 

Author Comment

by:tripsy
ID: 10849754
changing the way the connection is established, unfortunately doesn't change anything.

java consol output:
java.lang.NoClassDefFoundError: JApplet

      at java.lang.ClassLoader.defineClass0(Native Method)

      at java.lang.ClassLoader.defineClass(Unknown Source)

      at java.security.SecureClassLoader.defineClass(Unknown Source)

      at sun.applet.AppletClassLoader.findClass(Unknown Source)

      at java.lang.ClassLoader.loadClass(Unknown Source)

      at sun.applet.AppletClassLoader.loadClass(Unknown Source)

      at java.lang.ClassLoader.loadClass(Unknown Source)

      at sun.applet.AppletClassLoader.loadCode(Unknown Source)

      at sun.applet.AppletPanel.createApplet(Unknown Source)

      at sun.plugin.AppletViewer.createApplet(Unknown Source)

      at sun.applet.AppletPanel.runLoader(Unknown Source)

      at sun.applet.AppletPanel.run(Unknown Source)

      at java.lang.Thread.run(Unknown Source)

java.lang.NoClassDefFoundError: JApplet

      at java.lang.ClassLoader.defineClass0(Native Method)

      at java.lang.ClassLoader.defineClass(Unknown Source)

      at java.security.SecureClassLoader.defineClass(Unknown Source)

      at sun.applet.AppletClassLoader.findClass(Unknown Source)

      at java.lang.ClassLoader.loadClass(Unknown Source)

      at sun.applet.AppletClassLoader.loadClass(Unknown Source)

      at java.lang.ClassLoader.loadClass(Unknown Source)

      at sun.applet.AppletClassLoader.loadCode(Unknown Source)

      at sun.applet.AppletPanel.createApplet(Unknown Source)

      at sun.plugin.AppletViewer.createApplet(Unknown Source)

      at sun.applet.AppletPanel.runLoader(Unknown Source)

      at sun.applet.AppletPanel.run(Unknown Source)

      at java.lang.Thread.run(Unknown Source)

java.lang.NoClassDefFoundError: JApplet

      at java.lang.ClassLoader.defineClass0(Native Method)

      at java.lang.ClassLoader.defineClass(Unknown Source)

      at java.security.SecureClassLoader.defineClass(Unknown Source)

      at sun.applet.AppletClassLoader.findClass(Unknown Source)

      at java.lang.ClassLoader.loadClass(Unknown Source)

      at sun.applet.AppletClassLoader.loadClass(Unknown Source)

      at java.lang.ClassLoader.loadClass(Unknown Source)

      at sun.applet.AppletClassLoader.loadCode(Unknown Source)

      at sun.applet.AppletPanel.createApplet(Unknown Source)

      at sun.plugin.AppletViewer.createApplet(Unknown Source)

      at sun.applet.AppletPanel.runLoader(Unknown Source)

      at sun.applet.AppletPanel.run(Unknown Source)

      at java.lang.Thread.run(Unknown Source)






The browser itself displays:
Applet SchifferlVersenkenServer notinited
0
 
LVL 92

Expert Comment

by:objects
ID: 10851175
your applet reqiuires the java plugin to run.
you need to setup ie to use it as the default vm, or use the object tag instead of the applet tag.
0
 

Author Comment

by:tripsy
ID: 10853756
What kind of java plugin?
I'm using the NetBeans IDE 3.5.1, how do i set this up as my default vm?

I've tried changing APPLET to OBJECT in the html code, but it does't change anything.

thank you for your help!
0
 
LVL 92

Expert Comment

by:objects
ID: 10855570
> What kind of java plugin?

Sun's plugin http://www.java.com
0
 

Author Comment

by:tripsy
ID: 10859016
The problem is not in the vm, the vm is already installed and working properly. there is only an error in the browser when loading the applet.
0
 
LVL 92

Expert Comment

by:objects
ID: 10864534
But the VM is not finding the JApplet class, the Sun VM already has this class.
What VM is it running on?
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:tripsy
ID: 10866971
i have the java sun vm (netbeans is made by sun) ...
0
 
LVL 92

Expert Comment

by:objects
ID: 10873209
i know you have it, but is your browser using it.
Looking at that exception it appears not. Can you post the *complete* contents of the java console to confirm what vm it is using.
0
 

Author Comment

by:tripsy
ID: 10876136
0
 
LVL 92

Expert Comment

by:objects
ID: 10876171
thanks, so it is running the sun browser.
can u post the html
or better still can I access the applet somewhere on the web?
0
 
LVL 92

Expert Comment

by:objects
ID: 10876172
ignore that request for the html, just saw it in the q
0
 

Author Comment

by:tripsy
ID: 10896955
0
 
LVL 92

Accepted Solution

by:
objects earned 125 total points
ID: 10897067
put it back to the apoplet tag, theres more to it than switching applet to object.
the jdk comes with a htmlconverter tool to convert the html if u are interested.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now