JFrame中的问题

时间:2011-05-10 18:13:14

标签: java swing sockets jframe

我正在设计一个信使应用程序。我有一个正常运行的服务器程序。在客户端,首先我创建了GUI,其中包含文本窗格和文本字段。聊天工作正常。 然后我修改了客户端以支持登录工具,该工具提供登录文本字段,密码文本字段&签名按钮。 因此,在登录验证之后,当前JFrame是setVisible(false),并且应该显示带有聊天窗口的新JFrame并且并行地建立套接字连接。与服务器的套接字连接正确,但是不需要所需的GUI,即正确的JFrame。可能是什么问题?请..请帮助..

这是我的代码..

import java.net.*;
import java.io.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.text.*;
import javax.swing.event.*;


class Swing16 extends JPanel implements ActionListener
{

    public static JButton enterbutton,signin,chatbutton;
    public static JTextField txt,loginname,password;
    public static JTextPane textpane;
    public static JScrollPane sp;
    public static JLabel retrylabel;


    public static String str;
    public static String newline = "\n";
    public static String ss = "regular";

    public static StyledDocument doc,doc1;
    public static Icon icon1,icon2,icon3,icon4,icon5,icon6;

    public static InetAddress inet,newinet;
    public static Socket s,news;

    public static InputStream in,newin;
    public static OutputStream chatout,newout;

    public static BufferedReader newbr,chat;

    public static PrintWriter chatout1,newout1;
    public static int start;
    public static int end;
    public static int flag = 0;
    public static JFrame frm;


    class connecthread implements Runnable
    {
        Thread t;

        public connecthread()
        {
            t = new Thread(this);
            t.start();
        }

        public void run()
        {
            Swing16.makechatconnection();
        }
    }

    class alwaysrun implements Runnable
    {
        Thread t;

        public alwaysrun()
        {
            t = new Thread(this);
            t.start();
        }

        public void run()
        {
            Swing16.alwaystorun();
        }
    }


    public Swing16()
    {


        if(flag == 0)
        {
            enterbutton = new JButton("Enter");
            add(enterbutton);

            enterbutton.addActionListener(this);

        }


        else if(flag == 1)
        {


            loginname = new JTextField(10);
            add(loginname);

            password = new JTextField(10);
            add(password);


            signin = new JButton("SIGN IN");
            add(signin);

            signin.addActionListener(this);
        }


        else if(flag == 2)
        {

            chatbutton = new JButton("CHAT");
            add(chatbutton);
            chatbutton.addActionListener(this);

        }

        else if(flag == 3)
        {

            retrylabel = new JLabel("AUTHENTICATION FAILED! RETRY");
            add(retrylabel);


            loginname = new JTextField(10);
            add(loginname);

            password = new JTextField(10);
            add(password);


            signin = new JButton("SIGN IN");
            add(signin);

            signin.addActionListener(this);
        }




        else
        {

            GridBagLayout g = new GridBagLayout();
            setLayout(g);

            GridBagConstraints a = new GridBagConstraints();

            a.fill = GridBagConstraints.BOTH;
            a.weightx = 1.0;
            a.weighty = 1.0;
            textpane = new JTextPane();
            add(textpane,a);

            sp = new JScrollPane(textpane);
            a.gridwidth = GridBagConstraints.REMAINDER;
            a.fill = GridBagConstraints.BOTH;
            a.weightx = 1.0;
            a.weighty = 1.0;
            add(sp,a);
            textpane.setEditable(false);

            a.fill = GridBagConstraints.HORIZONTAL;
            a.anchor = GridBagConstraints.FIRST_LINE_START;
            txt = new JTextField(50);
            add(txt,a);

            icon1 = new ImageIcon("smile.png");
            icon2 = new ImageIcon("frown.png");
            icon3 = new ImageIcon("gasp.png");
            icon4 = new ImageIcon("grin.png");
            icon5 = new ImageIcon("tongue.png");
            icon6 = new ImageIcon("wink.png");


            txt.addActionListener(this);

            textpane.setEditorKit(new StyledEditorKit());
            Swing16.initListener();

            }

    }



    public void actionPerformed(ActionEvent ae)
    {


            String t;
            t = ae.getActionCommand();

            if(t.equals("Enter"))
            {

                flag = 1;
                frm.dispose();

                Swing16.makeGUI();

                /*try
                {

                    newinet = InetAddress.getLocalHost();
                    news = new Socket(newinet,1125);

                    newin = news.getInputStream();
                    newout = news.getOutputStream();


                    newout1 = new PrintWriter(new BufferedWriter(new OutputStreamWriter(newout)),true);
                    newbr = new BufferedReader(new InputStreamReader(newin));


                }
                catch(UnknownHostException e)
                {
                    System.out.println("Error.....!!!" + e);
                }
                catch(IOException e)
                {
                    System.out.println("Error....!!!" + e);
                }*/

            }

            else if(t.equals("SIGN IN"))
            {
                String name, passwd,authenticationcode;
                name = loginname.getText();
                passwd = password.getText();


                frm.dispose();

                try
                {
                    /*newout1.println(name);
                    newout1.println(passwd);

                    authenticationcode = newbr.readLine();
                    if(authenticationcode.equals("V"))
                    {
                    */

                        flag = 2;

                        /*newbr.close();
                        newout1.close();

                        newin.close();
                        newout.close();


                        news.close();


                    }

                    else
                        flag = 3; */            
                }
                catch(Exception e)
                {
                    System.out.println(e + "I am exception in sign in block in actionPerformed funation");
                }


                Swing16.makeGUI();
            }



            else if(t.equals("CHAT"))
            {

                frm.dispose();
                flag = 4;

                Swing16.makeGUI();

                new connecthread();

                new alwaysrun();

            }


            else
            {
                try
                {
                doc1 = textpane.getStyledDocument();
                str = txt.getText();
                try 
                {

                    doc1.insertString(doc1.getLength(),"Me:" + str + newline,doc1.getStyle(ss));

                    String text=doc1.getText(start, end-start);

                                    int i= text.indexOf(":)");

                    int j= text.indexOf(":(");

                    int k = text.indexOf(":O");

                    int l = text.indexOf(":D");

                    int m = text.indexOf(":P");

                    int n = text.indexOf(";)");

                    while(i>=0) 
                    {
                                            final SimpleAttributeSet attrs=new SimpleAttributeSet(doc1.getCharacterElement(start+i).getAttributes());

                        if (StyleConstants.getIcon(attrs)==null)
                        {
                                                StyleConstants.setIcon(attrs, icon1);
                                                doc1.remove(start+i, 2);
                                                doc1.insertString(start+i,":)", attrs);
                                            }

                    i=text.indexOf(":)", i+2);
                                    }

                    while(j>=0) 
                    {
                                            final SimpleAttributeSet attrs=new SimpleAttributeSet(doc1.getCharacterElement(start+j).getAttributes());

                        if (StyleConstants.getIcon(attrs)==null)
                        {
                                                StyleConstants.setIcon(attrs, icon2);
                                                doc1.remove(start+j, 2);
                                                doc1.insertString(start+j,":(", attrs);
                                            }

                    j=text.indexOf(":(", j+2);
                                    }

                    while(k>=0) 
                    {
                                            final SimpleAttributeSet attrs=new SimpleAttributeSet(doc1.getCharacterElement(start+k).getAttributes());

                        if (StyleConstants.getIcon(attrs)==null)
                        {
                                                StyleConstants.setIcon(attrs, icon3);
                                                doc1.remove(start+k, 2);
                                                doc1.insertString(start+k,":O", attrs);
                                            }

                    k=text.indexOf(":O", k+2);
                                    }

                    while(l>=0) 
                    {
                                            final SimpleAttributeSet attrs=new SimpleAttributeSet(doc1.getCharacterElement(start+l).getAttributes());

                        if (StyleConstants.getIcon(attrs)==null)
                        {
                                                StyleConstants.setIcon(attrs, icon4);
                                                doc1.remove(start+l, 2);
                                                doc1.insertString(start+l,":D", attrs);
                                            }

                    l=text.indexOf(":D", l+2);
                                    }

                    while(m>=0) 
                    {
                                            final SimpleAttributeSet attrs=new SimpleAttributeSet(doc1.getCharacterElement(start+m).getAttributes());

                        if (StyleConstants.getIcon(attrs)==null)
                        {
                                                StyleConstants.setIcon(attrs, icon5);
                                                doc1.remove(start+m, 2);
                                                doc1.insertString(start+m,":P", attrs);
                                            }

                    m=text.indexOf(":P", m+2);
                                    }   

                    while(n>=0) 
                    {
                                            final SimpleAttributeSet attrs=new SimpleAttributeSet(doc1.getCharacterElement(start+n).getAttributes());

                        if (StyleConstants.getIcon(attrs)==null)
                        {
                                                StyleConstants.setIcon(attrs, icon6);
                                                doc1.remove(start+n, 2);
                                                doc1.insertString(start+n,":P", attrs);
                                            }

                    n=text.indexOf(":P", n+2);
                                    }   

                }
                catch(NullPointerException e)
                {
                    System.out.println("I am d culprit");
                }
                catch (Exception ble)
                {
                        System.out.println(ble);
                }


                txt.setText("");
                chatout1.println(str);
            }
            catch(NullPointerException e)
            {
                    System.out.println("I am the culprit");
            }
            catch(Exception e)
            {
                System.out.println(e);
            }       

        }

  }




    public static void initListener()
    {

        textpane.getDocument().addDocumentListener(new DocumentListener(){

        public void insertUpdate(DocumentEvent event) 
        {

            final DocumentEvent e=event;


            if (e.getDocument() instanceof StyledDocument)
            {
                            try
                {
                                    //doc=(StyledDocument)e.getDocument();
                                    start= Utilities.getRowStart(textpane,Math.max(0,e.getOffset()-1));
                                    end=Utilities.getWordStart(textpane,e.getOffset()+e.getLength());
                                }
                catch (BadLocationException e1) 
                {
                                    e1.printStackTrace();
                                }
                        }


             }

        public void removeUpdate(DocumentEvent e) 
        {

         }

        public void changedUpdate(DocumentEvent event) 
        {

        }
        });
    }


    public static void makeGUI()
    {
        frm = new JFrame("Chat Window");
        frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frm.add(new Swing16());
        frm.pack();
        frm.setVisible(true);
    }



    public static void makechatconnection()
    {
        try
        {

            inet = InetAddress.getLocalHost();
            s = new Socket(inet,1125);

            in = s.getInputStream();
            chatout = s.getOutputStream();


            chatout1 = new PrintWriter(new BufferedWriter(new OutputStreamWriter(chatout)),true);

            chat = new BufferedReader(new InputStreamReader(in));
            if(chat == null)
            System.out.println("sskksks");

            chatout1.println("i get transmitted there..");
        }
        catch(UnknownHostException e)
        {
            System.out.println("Error.....!!!" + e);
        }
        catch(IOException e)
        {
            System.out.println("Error....!!!" + e);
        }
    }



    public static void alwaystorun()
    {
        try
            {

                while(true)
                {
                    String ss1=null;
                    ss1 = chat.readLine();
                    if(chat == null)
                    System.out.println("hey");
                    System.out.println(ss1);

                    try 
                    {
                            doc1 = textpane.getStyledDocument();

                        doc1.insertString(doc1.getLength(), ss1 + newline,doc1.getStyle(ss));

                        String text=doc1.getText(start, end-start);

                                        int i=text.indexOf(":)");
                        int j=text.indexOf(":(");

                        int k = text.indexOf(":O");

                        int l = text.indexOf(":D");

                        int m = text.indexOf(":P");

                        int n = text.indexOf(";)");

                        while(i>=0) 
                        {
                                                final SimpleAttributeSet attrs=new SimpleAttributeSet(doc1.getCharacterElement(start+i).getAttributes());

                            if (StyleConstants.getIcon(attrs)==null)
                            {
                                                    StyleConstants.setIcon(attrs, icon1);
                                                    doc1.remove(start+i, 2);
                                                    doc1.insertString(start+i,":)", attrs);
                                                }

                            i=text.indexOf(":)", i+2);
                                        }

                        while(j>=0) 
                        {
                                            final SimpleAttributeSet attrs=new SimpleAttributeSet(doc1.getCharacterElement(start+j).getAttributes());

                        if (StyleConstants.getIcon(attrs)==null)
                        {
                                                StyleConstants.setIcon(attrs, icon2);
                                                doc1.remove(start+j, 2);
                                                doc1.insertString(start+j,":(", attrs);
                                            }

                    j=text.indexOf(":(", j+2);
                                    }

                    while(k>=0) 
                    {
                                            final SimpleAttributeSet attrs=new SimpleAttributeSet(doc1.getCharacterElement(start+k).getAttributes());

                        if (StyleConstants.getIcon(attrs)==null)
                        {
                                                StyleConstants.setIcon(attrs, icon3);
                                                doc1.remove(start+k, 2);
                                                doc1.insertString(start+k,":O", attrs);
                                            }

                    k=text.indexOf(":O", k+2);
                                    }

                    while(l>=0) 
                    {
                                            final SimpleAttributeSet attrs=new SimpleAttributeSet(doc1.getCharacterElement(start+l).getAttributes());

                        if (StyleConstants.getIcon(attrs)==null)
                        {
                                                StyleConstants.setIcon(attrs, icon4);
                                                doc1.remove(start+l, 2);
                                                doc1.insertString(start+l,":D", attrs);
                                            }

                    l=text.indexOf(":D", l+2);
                                    }

                    while(m>=0) 
                    {
                                            final SimpleAttributeSet attrs=new SimpleAttributeSet(doc1.getCharacterElement(start+m).getAttributes());

                        if (StyleConstants.getIcon(attrs)==null)
                        {
                                                StyleConstants.setIcon(attrs, icon5);
                                                doc1.remove(start+m, 2);
                                                doc1.insertString(start+m,":P", attrs);
                                            }

                    m=text.indexOf(":P", m+2);
                                    }   

                    while(n>=0) 
                    {
                                            final SimpleAttributeSet attrs=new SimpleAttributeSet(doc1.getCharacterElement(start+n).getAttributes());

                        if (StyleConstants.getIcon(attrs)==null)
                        {
                                                StyleConstants.setIcon(attrs, icon6);
                                                doc1.remove(start+n, 2);
                                                doc1.insertString(start+n,":P", attrs);
                                            }

                    n=text.indexOf(":P", n+2);
                                    }   


                    }
                    catch (BadLocationException ble)
                    {
                            System.err.println("Couldn't insert text into text pane.");
                    }


                }
            }

            catch(Exception e)
            {
                System.out.println(e + "Something bad happened.");
            }


    }
    public static void main(String args[])
    {
        try
        {



            SwingUtilities.invokeLater(new Runnable()
            {
                        public void run()
                {
                    Swing16.makeGUI();

                }
            }
            );




        }
        catch(Exception e)
        {
            System.out.println(e);
        }
    }
}

2 个答案:

答案 0 :(得分:3)

我的猜测是你有一个并发问题,你没有在Swing主线程EDT背景的线程中进行套接字连接和通信,但这只是一个没有更多信息的猜测和代码。我建议您阅读Oracle Java教程中的Concurrency in Swing。一个制作精良的SwingWorker对象可以在这里很好地工作。

编辑1:
我在您的代码中看到的一些问题:

  • 您的代码应该没有静态字段,而是非静态实例变量。
  • 除了应该创建1个或几个实例的main方法之外,你的代码应该没有静态方法,然后在这些实例上调用适当的方法。
  • 你应该把这个上帝阶级分成几个较小的阶级,这样你才能分而治之。这使得调试变得更加容易,并且我们也能够更轻松地分析代码。
  • 你在“connectthread内部类中调用Swing15方法。这是一个印刷错误吗?
  • 你说你有一个NullPointerException。哪一行抛出这个?顺便说一下,你不应该尝试/捕获NullPointerExceptions。你找到它们并消除导致它们的问题。摆脱那个尝试/捕获。
  • 鉴于所有这些静态方法和字段,我打赌你是从另一种非OOP编程语言来到Java。我强烈建议你在Java中获得一些关于OOP编程的书籍,因为这将对你有很大的帮助。

答案 1 :(得分:2)

我猜您的Socket正在倾听 - 并且这会阻止您的应用,因此不会创建新的JFrame

我建议你开始Akka Actor (Java)并在actor中进行Socket连接。当actor接收消息时,使用SwingUtilities.invokeLater()将它们发布到事件派发线程上。