Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/user-interface/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PrintWriter对象Java聊天项目中的NullPointerException_Java_User Interface_Nullpointerexception_Chat_Drag - Fatal编程技术网

PrintWriter对象Java聊天项目中的NullPointerException

PrintWriter对象Java聊天项目中的NullPointerException,java,user-interface,nullpointerexception,chat,drag,Java,User Interface,Nullpointerexception,Chat,Drag,这是一个聊天服务器 我使用套接字编程创建了这个聊天服务器 我使用PrintWriter对象生成输出流 我的项目中有NullPointerException,但我不知道为什么! 出现异常的行是: output.println(jTextField1.getText()); 我尝试了所有我知道的,但我无法解决这个问题 有谁能给我一个解决办法吗 package chats; import java.io.IOException; import java.io.PrintWriter; import

这是一个聊天服务器 我使用套接字编程创建了这个聊天服务器 我使用PrintWriter对象生成输出流 我的项目中有NullPointerException,但我不知道为什么! 出现异常的行是:

output.println(jTextField1.getText());
我尝试了所有我知道的,但我无法解决这个问题 有谁能给我一个解决办法吗

package chats;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author princessaustralia
 */
public class ChatS extends javax.swing.JFrame implements Runnable
 {
        private Socket link = null;
    private ServerSocket server = null;
    private static int PORT = 4444;

    /**
     * Creates new form ChatS
     */
    public ChatS()
    {
        initComponents();
    }

    @Override
    public void run()
    {
        try
        {
            Scanner input;
            String message;
            server = new ServerSocket(PORT);
            link = server.accept();
            input = new Scanner(link.getInputStream());
            while (true)
            {
            message = input.nextLine();
            jTextArea1.setText(jTextArea1.getText() + "Client Says: " + message + "\n");
            jTextField1.setText("");
        }

    } catch (IOException ex)
    {
        ex.printStackTrace();
    }
}

/**
 * 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()
{

    jScrollPane1 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();
    jTextField1 = new javax.swing.JTextField();
    jButton1 = new javax.swing.JButton();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

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

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

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jScrollPane1)
        .addComponent(jTextField1)
        .addGroup(layout.createSequentialGroup()
            .addGap(159, 159, 159)
            .addComponent(jButton1)
            .addContainerGap(171, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 204, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(18, 18, 18)
            .addComponent(jButton1)
            .addGap(0, 12, Short.MAX_VALUE))
    );

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

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)                                         
{                                             
    try
    {
        PrintWriter output;
        output = new PrintWriter(link.getOutputStream(), true);
        jTextArea1.append("You Sayed: " + jTextField1.getText());
        output.println(jTextField1.getText());
        output.flush();
        jTextField1.setText("");
    } catch (IOException ex)
    {
        Logger.getLogger(ChatS.class.getName()).log(Level.SEVERE, null, ex);
    }
}                                        

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

// Variables declaration - do not modify                     
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
// End of variables declaration                   


}

您获得NPE是因为您的链接为空

您将客户机套接字与服务器套接字混为一谈。服务器正在等待接受连接。您这样做了,好吧,但是在Swing应用程序中

应该有这样的文字

Socket socket = new Socket("localhost", 4444);
//get the io streams and talk to the server
也许这样行得通:

PrintWriter output;
Socket socket = new Socket("localhost", 4444);
output = new PrintWriter(socket.getOutputStream(), true);
但那时应用程序会自言自语

好的,给你:

private Socket link = null;
private ServerSocket server = null;
private static int PORT = 4444;

/**
 * Creates new form ChatS
 */
public ChatS() {
this.initComponents();
new Thread(this).start();
}

@Override
public void run() {
try {
    Scanner input;
    String message;
    this.server = new ServerSocket(PORT);

    while (true) {
    this.link = this.server.accept();
    input = new Scanner(this.link.getInputStream());
    message = input.nextLine();
    System.out.println(message);
    this.jTextArea1.setText(this.jTextArea1.getText() + "Client Says: " + message + "\n");
    this.jTextField1.setText("");
    }

} catch (final IOException ex) {
    ex.printStackTrace();
}
}

/**
 * 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() {

this.jScrollPane1 = new javax.swing.JScrollPane();
this.jTextArea1 = new javax.swing.JTextArea();
this.jTextField1 = new javax.swing.JTextField();
this.jButton1 = new javax.swing.JButton();

this.setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

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

this.jButton1.setText("Send");
this.jButton1.addActionListener(new java.awt.event.ActionListener() {
    @Override
    public void actionPerformed(final java.awt.event.ActionEvent evt) {
    ChatS.this.jButton1ActionPerformed(evt);
    }
});

final javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this.getContentPane());
this.getContentPane().setLayout(layout);
layout.setHorizontalGroup(layout
    .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addComponent(this.jScrollPane1)
    .addComponent(this.jTextField1)
    .addGroup(
        layout.createSequentialGroup().addGap(159, 159, 159).addComponent(this.jButton1)
            .addContainerGap(171, Short.MAX_VALUE)));
layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(
    layout.createSequentialGroup()
        .addComponent(this.jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 204,
            javax.swing.GroupLayout.PREFERRED_SIZE)
        .addGap(18, 18, 18)
        .addComponent(this.jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 28,
            javax.swing.GroupLayout.PREFERRED_SIZE).addGap(18, 18, 18).addComponent(this.jButton1)
        .addGap(0, 12, Short.MAX_VALUE)));

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

private void jButton1ActionPerformed(final java.awt.event.ActionEvent evt) {
try {
    PrintWriter output;
    final Socket socket = new Socket("localhost", 4444);
    output = new PrintWriter(socket.getOutputStream(), true);
    this.jTextArea1.append("You Sayed: " + this.jTextField1.getText());
    output.println(this.jTextField1.getText());
    output.flush();
    this.jTextField1.setText("");
} catch (final IOException ex) {
    // Logger.getLogger(ChatS.class.getName()).log(Level.SEVERE, null,
    // ex);
}
}

/**
 * @param args
 *            the command line arguments
 */
public static void main(final String args[]) {
/* 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 (final javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
    if ("Nimbus".equals(info.getName())) {
        javax.swing.UIManager.setLookAndFeel(info.getClassName());
        break;
    }
    }
} catch (final ClassNotFoundException ex) {
    java.util.logging.Logger.getLogger(ChatS.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (final InstantiationException ex) {
    java.util.logging.Logger.getLogger(ChatS.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (final IllegalAccessException ex) {
    java.util.logging.Logger.getLogger(ChatS.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (final javax.swing.UnsupportedLookAndFeelException ex) {
    java.util.logging.Logger.getLogger(ChatS.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
// </editor-fold>

/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
    @Override
    public void run() {
    new ChatS().setVisible(true);
    }
});
}

// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
首先,您必须通过新线程this.start;启动线程;。请参阅构造函数

接下来,您应该为每个套接字请求创建一个服务器套接字。请参阅方法运行

最后,您必须如上所述在客户端创建一个套接字


工作…

哪一行引发异常?您是否在Eclipse中使用调试选项?我猜您是在eclispe中编写的。@poodle它看起来更像是在NetBeans中编写/生成的这一行:output.printlnjTextField1.getText;格式化你的代码。删除不必要的netbean生成的代码我写了这个:Socket link。。。但异常仍然出现:她正在用run方法初始化它。所以它不可能是因为空链接。link=server.accept;我刚做了一个System.out.printlnlink是+link;就在输出之前=new PrintWriterlink.getOutputStream,true;在她的代码中,它说link是null.link是null异常,线程AWT-EventQueue-0java.lang.NullPointerException在example.ChatS.jButton1ActionPerformedChatS.java:113在example.ChatS.access$0ChatS.java:107在example.ChatS$1.actionPerformedChatS.java:78I真的感谢您。。。但出现了新的异常:D。。。java.net.SocketException:套接字未连接啊,正常。我认为这是由于这样一个事实,即您在服务器端只有一个链接引用的连接。还有很多工作要做,比如创建一个类扩展线程来推动套接字连接。然后使用HashMap之类的集合来保存所有线程asf。。无论如何,我不能在这里重现这个例外。因此,这应该是一个良好的开端。