Swing聊天窗口创建了额外的聊天窗口

时间:2013-07-23 15:44:28

标签: java swing client-server chat

我正在为我正在处理的项目的聊天部分制作一个简单的GUI。我希望为对话建立一个聊天窗口,但由于某种原因,每次运行调用线程的main方法时,都会弹出2个额外的窗口(每个thread 1个,我会假设)。

到目前为止,我有以下内容:

   package udpcs1;

   import java.awt.BorderLayout;
   import java.awt.event.ActionEvent;
   import java.awt.event.ActionListener;
   import javax.swing.JButton;
   import javax.swing.JFrame;
   import javax.swing.JScrollPane;
   import javax.swing.JTextArea;
   import javax.swing.JTextField;

   public class UDPCS1 implements ActionListener {

      private static String csMsg1 = "";
      private static int played = 0;
      private static UDPCS1 chat = new UDPCS1();
      private final JFrame f = new JFrame();
      private final JTextField tf = new JTextField(60);
      private final JTextArea textArea = new JTextArea(10, 60);
      private final JButton send = new JButton("Send");

      protected String[] message = { ... };

      protected String[] rps = { ... };

      public UDPCS1() {
          f.setTitle("Chat");
          f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          f.getRootPane().setDefaultButton(send);
          f.add(tf, BorderLayout.NORTH);
          f.add(new JScrollPane(textArea), BorderLayout.CENTER);
          f.add(send, BorderLayout.SOUTH);
          f.setLocation(400, 300);
          f.pack();
          send.addActionListener(this);
          textArea.setLineWrap(true);
          textArea.setWrapStyleWord(true);
          f.setVisible(true);
      }

      @Override
      public void actionPerformed(ActionEvent event) {
          String msg = tf.getText();
          display(msg);
          tf.setText("");
      }

      // Server/client thread already synchronize their output, so only need to display it
      protected void display(final String s){
                  textArea.append(s + "\n");
      }

      protected UDPCS1 getChat() {
                  return chat;
      }

      // get/set methods for some intra-host communication
      protected String getMsg() { ... }
      protected void setMsg(String newMsg) { ... }
      protected int getNum() { ... }
      protected void incNum() { ... }

      public static void main(String[] args) throws Exception {
      // Start the first server-client pair
      UDPServer1 server1 = new UDPServer1();
      UDPClient1 client1 = new UDPClient1();
      }
  }

我的服务器和客户端都扩展了此class,然后在希望输出到聊天窗口时调用getChat().display(String s)。但是,与此同时,我得到3个初始聊天窗口(可能完全是因为我扩展它)。但是,我确实需要这个类的一些功能,所以我需要它成为一个超类。如果不获得3个聊天窗口,我可以做些什么来保持整体功能不变?

PS。我意识到使用静态变量被认为是一个严重的罪恶,但我无法想出任何其他方式让客户端和服务器都可以轻松访问这些变量。关于改进方法的建议也是最受欢迎的。


编辑:从f.setVisible(true);构造函数中移除UDPCS1,制作f static,然后从内部调用f.setVisible(true); UDPCS1线程(初始程序)似乎解决了这个问题,因为只出现一个聊天窗口,客户端和服务器都与之通信。但是,我确信必须有一个更好/更少出错/更清洁的方法来做到这一点。我还在等待任何答案和评论。

1 个答案:

答案 0 :(得分:0)

只需从static中移除private static UDPCS1 chat = new UDPCS1();关键字,就不会再有聊天窗口了...... 希望它有所帮助...

在我的情况下,我也做了一件事,......

相关问题