簡體   English   中英

實現套接字方法后,Java GUI沒有出現

[英]Java GUI not appearing after implementing socket methods

我的代碼沒有錯誤。 只要將我創建的start方法中的代碼注釋掉,代碼就可以正常工作。 我不確定為什么會這樣。 我嘗試過移動代碼,但不能解決問題。 為什么啟動方法中的代碼阻止GUI在屏幕上顯示?

package my.IPMessenger;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
 *
 * 
 */
public class IPMessengerGUI extends javax.swing.JFrame {
    static ServerSocket SC;
    static Socket socket;
    static BufferedReader in;
    static DataOutputStream out;
    static char[] c;
    static String text;
    static String iP;
    static Socket sock2;
    static BufferedReader in2;
    static DataOutputStream out2;
    static InetAddress address;

    /**
     * Creates new form IPMessengerGUI
     */
    public IPMessengerGUI() throws IOException {
        start();
        initComponents();
        jTextArea1.setLineWrap(true);
        jTextArea2.setLineWrap(true);
//        SC = new ServerSocket(6850);
//  socket = SC.accept();
//  socket.setKeepAlive(true);
//  in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//  out = new DataOutputStream(socket.getOutputStream());
//  c = new char[1000];
//        in2 = new BufferedReader(new InputStreamReader(sock2.getInputStream()));
//        out2 = new DataOutputStream(sock2.getOutputStream());
//        search();
    }
    private void start() throws IOException{
        SC = new ServerSocket(6850);
    socket = SC.accept();
    socket.setKeepAlive(true);
    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    out = new DataOutputStream(socket.getOutputStream());
    c = new char[1000];
        in2 = new BufferedReader(new InputStreamReader(sock2.getInputStream()));
        out2 = new DataOutputStream(sock2.getOutputStream());
        search();   
    }


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

        jScrollPane2 = new javax.swing.JScrollPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTextArea2 = new javax.swing.JTextArea();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenu2 = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane1.setViewportView(jTextArea1);

        jScrollPane2.setViewportView(jScrollPane1);

        jTextArea2.setColumns(20);
        jTextArea2.setRows(5);
        jScrollPane3.setViewportView(jTextArea2);

        jLabel1.setText("jLabel1");

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

        jButton2.setText("jButton2");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jMenu1.setText("File");
        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        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(91, 91, 91)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 250, Short.MAX_VALUE)
                    .addComponent(jScrollPane3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton1)
                .addContainerGap(97, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jButton2))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jButton2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 38, Short.MAX_VALUE)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1)))
        );

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

    private void search() throws IOException{

        while(true){
            if(in.ready()){
                in.read(c);
             for(int count = 0; count < c.length ; count++){
                text += c[count]; 
             }  
            jTextArea2.append(text);
            }
        }
    }

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        jTextArea2.append(" " + jTextArea1.getText());

        try {

            out.writeChars(jTextArea1.getText());
        } catch (NullPointerException|IOException ex) {

        }
        jTextArea1.setText(null);
    }                                        

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        String ip =( JOptionPane.showInputDialog(null, "please enter a valid IP address:"));
        int convert = Integer.parseInt(ip);
        byte[] bytes = BigInteger.valueOf(convert).toByteArray();
        try {
             address = InetAddress.getByAddress(bytes);
        } catch (UnknownHostException ex) {
            Logger.getLogger(IPMessengerGUI.class.getName()).log(Level.SEVERE, null, ex);
        }
        try {
            sock2 = new Socket(address,6850);
            sock2.setKeepAlive(true);
        } catch (IOException ex) {
            Logger.getLogger(IPMessengerGUI.class.getName()).log(Level.SEVERE, null, ex);
        }
    }                                        

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) throws IOException {
        /* 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(IPMessengerGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(IPMessengerGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(IPMessengerGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(IPMessengerGUI.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() {

                try {

                    new IPMessengerGUI().setVisible(true);

                } catch (IOException ex) {
                    Logger.getLogger(IPMessengerGUI.class.getName()).log(Level.SEVERE, null, ex);
                }

            }

        });

    }

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextArea jTextArea2;
    // End of variables declaration                   
}

在我看來,您實際上從未真正接觸過代碼的GUI部分。 您可能要在這里使用一些多線程,因為這似乎是您的目標。 在構造函數中,您正在調用start方法-到目前為止一切都很好-似乎可以按預期執行。 但是 ,當您在start()的末尾調用search()時,它會進入一個無限循環(參數為true )。 您的循環邏輯阻止了search()的返回,從而阻止了start()的返回,然后是構造函數的返回。 希望對您有所幫助,並祝您好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM