Java – 使用AWT来更改JFrame的标题

huangapple go评论70阅读模式
英文:

Java - Using AWT to change title of JFrame

问题

我正在编写一个简单的多线程客户端/服务器聊天系统项目要求如下:“只有在单击连接按钮时才会建立连接断开连接按钮应断开连接用户在按下连接按钮之前输入用户名一旦获取了用户名还应将其添加到框架的标题栏中。” 基本上我已经连接了并且运行正常当用户输入名称并按下连接按钮时我该如何更改主框架的标题 请帮忙这是我第一个套接字编程项目我在这个问题上完全被卡住了谢谢大家

客户端


    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import java.util.ArrayList;
    
    public class ClientFrame extends Frame {
    
        public ClientFrame() {
            setSize(500, 500);
            setTitle("Chat Client");
            addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent We) {
                    System.exit(0);
                }
            });
            add(new ClientPanel(), BorderLayout.CENTER);
            setVisible(true);
        }
    
        public static void main(String[] args) {
            new ClientFrame();
        }
    
    } // end ClientFrame
    
    class ClientPanel extends Panel implements ActionListener, Runnable {
    
        TextField tf;
        TextArea ta;
        List list;
        Button connect, disconnect;
        Socket socketToServer;
        PrintWriter pw;
        BufferedReader br;
        Thread t;
        String userName;
    
        public ClientPanel() {
            setLayout(new BorderLayout());
            tf = new TextField();
            ta = new TextArea();
            list = new List();
            connect = new Button("Connect");
            disconnect = new Button("Disconnect");
            Panel bPanel = new Panel();
            bPanel.add(connect);
            disconnect.setEnabled(false);
            bPanel.add(disconnect);
    
            tf.addActionListener(this);
            add(tf, BorderLayout.NORTH);
            add(ta, BorderLayout.CENTER);
            add(list, BorderLayout.EAST);
            add(bPanel, BorderLayout.SOUTH);
    
            connect.addActionListener(this);
            disconnect.addActionListener(this);
    
        } // end ClientPanel constructor
    
        public void actionPerformed(ActionEvent ae) {
            if (ae.getSource() == tf) {
                System.out.println(tf + " " + tf.getText());
                String temp = tf.getText();
    
                pw.println(userName + ": " + temp);
                tf.setText("");
            } else if (ae.getSource() == connect) {
                if (tf.getText() == null || tf.getText().equals("")) {
                    ta.append("Must enter a name to connect\n");
                } else {
                    userName = tf.getText();
                    connect.setEnabled(false);
                    disconnect.setEnabled(true);
                    tf.setText("");
                    try {
                        socketToServer = new Socket("127.0.0.1", 3000);
                        pw = new PrintWriter(new OutputStreamWriter(socketToServer.getOutputStream()), true);
                        br = new BufferedReader(new InputStreamReader(socketToServer.getInputStream()));
                    } catch (UnknownHostException uhe) {
                        System.out.println(uhe.getMessage());
                    } catch (IOException ioe) {
                        System.out.println(ioe.getMessage());
                    }
                }
    
                t = new Thread(this);
                t.start();
                pw.println(userName);
                pw.println(userName + " has entered the chat.");
            } else if (ae.getSource() == disconnect) {
                   connect.setEnabled(true);
                    disconnect.setEnabled(false);
                try {
                    tf.setText("");
                    try {
                        socketToServer = new Socket("127.0.0.1", 3000);
                        pw = new PrintWriter(new OutputStreamWriter(socketToServer.getOutputStream()), true);
                        br = new BufferedReader(new InputStreamReader(socketToServer.getInputStream()));
                    } catch (UnknownHostException uhe) {
                        System.out.println(uhe.getMessage());
                    } catch (IOException ioe) {
                        System.out.println(ioe.getMessage());
                    }
    
                    t = new Thread(this);
                    t.start();
                    pw.println(userName);
                    pw.println(userName + " has Disconnected the chat.");
                 
                    t.interrupt();
                    socketToServer.close();
                } catch (IOException ioe) {
                    System.out.println(ioe.getMessage());
                }
            }
        } // end actionPerformed
    
        public void run() {
            try {
                for (;;) {
                    try {
                        String temp = br.readLine();
                        ta.append(temp + "\n");
    
                    } catch (IOException ioe) {
                        System.out.println(ioe.getMessage());
    
                    }
                    Thread.sleep(10);
                }
            } catch (InterruptedException e) {
                pw.println("Disconnected.");
            }
        } // end run
    
    } // end ClientPanel


Server:

    

    import java.io.*;
    import java.net.*;
    import java.util.ArrayList;
    import java.awt.*;
    
    public class ThreadedServerWithPresence {
    
        public static void main(String[] args) {
            ArrayList<ThreadedHandlerWithPresence> handlers;
            try {
                handlers = new ArrayList<ThreadedHandlerWithPresence>();
                ServerSocket s = new ServerSocket(3000);
                for (;;) {
                    Socket incoming = s.accept();
                    new ThreadedHandlerWithPresence(incoming,
                            handlers).start();
    
                }
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }
    
    class ThreadedHandlerWithPresence extends Thread {
    
        Socket incoming;
        ArrayList<ThreadedHandlerWithPresence> handlers;
        PrintWriter pw;
        BufferedReader br;
        String userName;
    
        public ThreadedHandlerWithPresence(Socket i,
                ArrayList<ThreadedHandlerWithPresence> handlers) {
            incoming = i;
            this.handlers = handlers;
            handlers.add(this);
        }
    
        public void setUserName(String userName) {
            this.userName = userName;
        }
    
        public String getUserName() {
            return userName;
        }
    
        public void run() {
            try {
                br = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
    
                pw = new PrintWriter(new OutputStreamWriter(incoming.getOutputStream()), true);
    
                String firstLine = br.readLine();
                setUserName(firstLine);
    
                for (;;) {
    
                    String temp = br.readLine();
                    if (temp == null) {
                        break;
                    }
                    System.out.println("Message read: " + temp);
    
                    for (int i = 0; i < handlers.size(); i++) {
                        handlers.get(i).pw.println(temp);
                    }
                }
            } catch (Exception e) {
                System.out.println(e);
            } finally {
                handlers.remove(this);
            }
        }
    }
英文:

I am programming a simple multi-threaded client/server chat system. Project requirements specify: "Connection only happens when the connect button is clicked. The disconnect button should disconnect the connection.User enters Username before pressing connect button, Once the userName has been retrieved as above, it should also be added to the Titlebar of the Frame. " Basically, I have the connect button hooked-up and running.When user enter his name and presses Connect , How can I change title of Main Frame. Please help, this is my first socket programming project and I am super stumped on this one! Thanks all.

Client:

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.ArrayList;
public class ClientFrame extends Frame {
public ClientFrame() {
setSize(500, 500);
setTitle(&quot;Chat Client&quot;);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent We) {
System.exit(0);
}
});
add(new ClientPanel(), BorderLayout.CENTER);
setVisible(true);
}
public static void main(String[] args) {
new ClientFrame();
}
} // end ClientFrame
class ClientPanel extends Panel implements ActionListener, Runnable {
TextField tf;
TextArea ta;
List list;
Button connect, disconnect;
Socket socketToServer;
PrintWriter pw;
BufferedReader br;
Thread t;
String userName;
public ClientPanel() {
setLayout(new BorderLayout());
tf = new TextField();
ta = new TextArea();
list = new List();
connect = new Button(&quot;Connect&quot;);
disconnect = new Button(&quot;Disconnect&quot;);
Panel bPanel = new Panel();
bPanel.add(connect);
disconnect.setEnabled(false);
bPanel.add(disconnect);
tf.addActionListener(this);
add(tf, BorderLayout.NORTH);
add(ta, BorderLayout.CENTER);
add(list, BorderLayout.EAST);
add(bPanel, BorderLayout.SOUTH);
connect.addActionListener(this);
disconnect.addActionListener(this);
} // end ClientPanel constructor
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == tf) {
System.out.println(tf + &quot; &quot; + tf.getText());
String temp = tf.getText();
pw.println(userName + &quot;: &quot; + temp);
tf.setText(&quot;&quot;);
} else if (ae.getSource() == connect) {
if (tf.getText() == null || tf.getText().equals(&quot;&quot;)) {
ta.append(&quot;Must enter a name to connect\n&quot;);
} else {
userName = tf.getText();
connect.setEnabled(false);
disconnect.setEnabled(true);
tf.setText(&quot;&quot;);
try {
socketToServer = new Socket(&quot;127.0.0.1&quot;, 3000);
pw = new PrintWriter(new OutputStreamWriter(socketToServer.getOutputStream()), true);
br = new BufferedReader(new InputStreamReader(socketToServer.getInputStream()));
} catch (UnknownHostException uhe) {
System.out.println(uhe.getMessage());
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
}
t = new Thread(this);
t.start();
pw.println(userName);
pw.println(userName + &quot; has entered the chat.&quot;);
} else if (ae.getSource() == disconnect) {
connect.setEnabled(true);
disconnect.setEnabled(false);
try {
tf.setText(&quot;&quot;);
try {
socketToServer = new Socket(&quot;127.0.0.1&quot;, 3000);
pw = new PrintWriter(new OutputStreamWriter(socketToServer.getOutputStream()), true);
br = new BufferedReader(new InputStreamReader(socketToServer.getInputStream()));
} catch (UnknownHostException uhe) {
System.out.println(uhe.getMessage());
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
t = new Thread(this);
t.start();
pw.println(userName);
pw.println(userName + &quot; has Disconnected the chat.&quot;);
t.interrupt();
socketToServer.close();
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
}
} // end actionPerformed
public void run() {
try {
for (;;) {
try {
String temp = br.readLine();
ta.append(temp + &quot;\n&quot;);
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
Thread.sleep(10);
}
} catch (InterruptedException e) {
pw.println(&quot;Disconnected.&quot;);
}
} // end run
} // end ClientPanel

Server:

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.awt.*;
public class ThreadedServerWithPresence {
public static void main(String[] args) {
ArrayList&lt;ThreadedHandlerWithPresence&gt; handlers;
try {
handlers = new ArrayList&lt;ThreadedHandlerWithPresence&gt;();
ServerSocket s = new ServerSocket(3000);
for (;;) {
Socket incoming = s.accept();
new ThreadedHandlerWithPresence(incoming,
handlers).start();
}
} catch (Exception e) {
System.out.println(e);
}
}
}
class ThreadedHandlerWithPresence extends Thread {
Socket incoming;
ArrayList&lt;ThreadedHandlerWithPresence&gt; handlers;
PrintWriter pw;
BufferedReader br;
String userName;
public ThreadedHandlerWithPresence(Socket i,
ArrayList&lt;ThreadedHandlerWithPresence&gt; handlers) {
incoming = i;
this.handlers = handlers;
handlers.add(this);
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserName() {
return userName;
}
public void run() {
try {
br = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
pw = new PrintWriter(new OutputStreamWriter(incoming.getOutputStream()), true);
String firstLine = br.readLine();
setUserName(firstLine);
for (;;) {
String temp = br.readLine();
if (temp == null) {
break;
}
System.out.println(&quot;Message read: &quot; + temp);
for (int i = 0; i &lt; handlers.size(); i++) {
handlers.get(i).pw.println(temp);
}
}
} catch (Exception e) {
System.out.println(e);
} finally {
handlers.remove(this);
}
}
}

答案1

得分: 0

这很简单。如果你的类已扩展为 Frame,你可以简单地将 ClientFrame 类传递给 ClientPanel,就像这样:

add(new ClientPanel(this), BorderLayout.CENTER);

在 ClientPanel 构造函数中,你可以这样做:

JFrame clientFrame;

public ClientPanel(JFrame clientFrame) {
    this.clientFrame = clientFrame;
}

最后,你调用所需的方法:

clientFrame.setTitle(userName);
英文:

It's simple. If you have your class extended to Frame you can just simply pass the ClientFrame class to the ClientPanel like this:

add(new ClientPanel(this), BorderLayout.CENTER);

In the ClientPanle constructor you can do something like this:

JFrame clientFrame;
public ClientPanel(JFrame clientFrame) {
this.clientFrame=clientFrame;

Finally you call the desired method:

clientFrame.setTitle(userName);

huangapple
  • 本文由 发表于 2020年7月27日 18:23:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/63113326.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定