【问题标题】:Problem in JFramesJFrame 中的问题
【发布时间】:2011-08-22 16:57:36
【问题描述】:

我正在设计一个信使应用程序。我有一个正常运行的服务器程序。在客户端,首先我创建了由文本窗格和文本字段组成的 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);
        }
    }
}

【问题讨论】:

  • 如果您能提供 som 代码会很有帮助。
  • 代码已发布。请帮忙。
  • 请参阅我帖子的编辑 1。

标签: java swing sockets jframe


【解决方案1】:

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

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

  • 您的代码不应包含静态字段,而应包含非静态实例变量。
  • 除了应该创建 1 个或几个实例然后在这些实例上调用适当方法的 main 方法之外,您的代码不应有任何静态方法。
  • 你应该把这个神级分解成几个更小的类,这样你就可以分而治之了。这让调试变得更加容易,我们也更容易分析您的代码。
  • 您在“connectthread 内部类”中调用了 Swing15 方法。这是印刷错误吗?
  • 你说你有一个 NullPointerException。哪条线抛出这个?顺便说一句,您不应该尝试/捕获 NullPointerExceptions。您找到它们并消除导致它们的问题。摆脱那种尝试/捕捉。
  • 鉴于所有这些静态方法和字段,我敢打赌您是从另一种非 OOP 编程语言转向 Java。我强烈建议您购买一些有关用 Java 进行 OOP 编程的书籍,因为这将极大地帮助您。

【讨论】:

  • 感谢您的建议...n 是的..我是 JAVA 新手。函数 alwaystorun 给出空指针异常。
  • @Ameya:但是哪一行给出了异常。您必须删除 try/catch(NullPointException) 才能找出答案。
  • 我将根据您的建议进行必要的更改,稍后在 d 代码中。但我需要通过 tmrw 完成此代码。所以请帮我找出它现在不起作用的原因。
  • 第 519 行,即包含语句 ss1=chat.readLine() 的行给出了该异常。
  • @Ameya:所以聊天变量在 NPE (NullPointerExceptio) 时为空。现在你必须检查你的代码并找出原因。您可能需要在整个代码中添加更多 println 语句来帮助您。
【解决方案2】:

我猜你的 Socket 正在监听 - 这会阻止你的应用程序,因此不会创建新的 JFrame

我建议你启动一个Akka Actor (Java) 并在actor 中进行Socket 连接。当actor收到消息时,您使用SwingUtilities.invokeLater()将它们发布到事件调度线程。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-29
    • 2014-10-28
    • 1970-01-01
    相关资源
    最近更新 更多