简体   繁体   中英

How to use random number from server to randomly display image from an array of images on client JAVA SOCKET PROGRAMMING

I have this project where I have to take random number from server and use it to randomly display a picture from an array on client side a button click. So basically this random number from server should be the index of some image from array of images.

Here is the server:


    public class MemoryGameServer {
    public int[] array; 


    //Method to generate random number 

    public int getRandom(){
        this.array = new int[4];
       Random random = new Random();
        int randomNumber = random.nextInt(array.length);
        return randomNumber;
    } 






    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception {
        ServerSocket listener = new ServerSocket(1243);
        System.out.println("Server is connected..");
        try {
            while (true) {
                Socket socket = listener.accept();
                System.out.println("Client is connected..");
                MemoryGameServer server = new MemoryGameServer();

                DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
                dos.writeInt(server.getRandom()); // Sending random number as integer
                dos.flush();


            }
        } catch (IOException ex) {
            System.out.println(ex);
        }
    }
} 

Here is the client:

public class MemoryGameClient extends javax.swing.JFrame {

  public String[] images = {"0.jpg", "1.jpg", "2.jpg", "3.jpg"};
  public int n;
  Socket socket;



    public int randomPicture () throws IOException{

        try{

        DataInputStream dis = new DataInputStream(socket.getInputStream());

        this.n = dis.readInt();
        System.out.println("Random number form server: " +n);





        } catch (Exception ex){

        }
        return n;
    }



    /**
     * Creates new form MemoryGameClient
     */
    public MemoryGameClient() {
        initComponents();

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

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

        jButton2.setText("2x4");

        jLabel1.setName("lblImage"); // NOI18N

        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(54, 54, 54)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 178, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 89, Short.MAX_VALUE)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(64, 64, 64))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(20, 20, 20))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 210, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(29, 29, 29))
        );

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

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


          //String image1 = images[randomImage1];
          jLabel1.setIcon(new ImageIcon("src\\Images\\" ));
          //jLabel2.setIcon(new ImageIcon("src\\Images\\" +image));
          //jLabel3.setIcon(new ImageIcon("src\\Images\\" +image1));
          //jLabel4.setIcon(new ImageIcon("src\\Images\\" +image1));





    }                                        

    /**
     * @param args the command line arguments
     */

    public void connectToServer() throws IOException {

        // Get the server address from a dialog
// box.
        String serverAddress = "localhost";

        // Make connection and initialize streams
        try{
        socket = new Socket("localhost", 1243);

                /* InputStream is = socket.getInputStream();

                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                this.str = br.readLine();
                System.out.println("Random number form server: " +str);

                */

        } catch(Exception ex)
        { 
            JOptionPane.showMessageDialog(this, "Nema servera");
        }
    }
    public static void main(String args[]) throws IOException {

        MemoryGameClient client = new MemoryGameClient();
        client.setVisible(true);
        client.connectToServer();
        client.randomPicture();


        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MemoryGameClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MemoryGameClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MemoryGameClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MemoryGameClient.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {

            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    // End of variables declaration                   
}

It is sending random number to the client, i just don't know how to use that number to take a random image from this String [] images array. It should work on the click of the button 2x2 or 2x4 (i have later to make it display 2x2 or 2x4 pictures, but i can do it on my own).

Thanks for helping.

 int num = new Random().nextInt(4) + 1;// would represent a random number between 1-4.

switch (num) {
            case 0:
                jLabel1.setIcon(new ImageIcon("src\\Images\\"+images[num]));
                break;
            case 1:
                jLabel2.setIcon(new ImageIcon("src\\Images\\"+images[num]));
                break;
            case 2:
                jLabel3.setIcon(new ImageIcon("src\\Images\\"+images[num]));
                break;
            case 3:
                jLabel4.setIcon(new ImageIcon("src\\Images\\"+images[num]));
                break;
            default:
                //error
        }

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM