上述代码不使用继承的实例
时间: 2023-08-23 17:03:53 浏览: 46
好的,以下是一个不使用继承的 Java 实例,其中包含 `JFrame`、`JButton`、`JTextArea` 等界面方法:
```java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class GUIExample {
private JFrame frame;
private JButton connectButton;
private JTextArea messageArea;
public GUIExample() {
frame = new JFrame("Socket Client"); // 创建窗口
frame.setSize(400, 300); // 设置窗口大小
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 设置窗口关闭操作
// 创建连接按钮
connectButton = new JButton("Connect");
connectButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
connect(); // 点击按钮时调用 connect() 方法
}
});
// 创建消息显示区域
messageArea = new JTextArea();
messageArea.setEditable(false); // 设置为只读
// 将按钮和消息区域添加到窗口中
frame.add(connectButton, BorderLayout.NORTH);
frame.add(new JScrollPane(messageArea), BorderLayout.CENTER);
}
private void connect() {
String hostname = "localhost"; // 服务器地址
int port = 8080; // 服务器端口号
try {
messageArea.append("Connecting to server: " + hostname + ", port: " + port + "\n");
// 创建客户端 Socket
// 省略其它代码,具体实现可参考前面的示例
messageArea.append("Connected to server: " + clientSocket.getRemoteSocketAddress() + "\n");
// 向服务器发送消息
writer.write("Hello from " + clientSocket.getLocalSocketAddress() + "\n");
writer.flush(); // 刷新缓冲区
// 读取服务器响应
String response = reader.readLine();
messageArea.append("Server response: " + response + "\n");
clientSocket.close(); // 关闭客户端 Socket
} catch (IOException e) {
e.printStackTrace();
}
}
public void show() {
frame.setVisible(true); // 显示窗口
}
public static void main(String[] args) {
GUIExample gui = new GUIExample();
gui.show(); // 显示窗口
}
}
```
上述代码中,我们没有使用继承 `JFrame`,而是将其作为 GUIExample 类的一个成员变量。在构造函数中,我们创建了连接按钮和消息显示区域,并将它们添加到窗口中。
在 `connect()` 方法中,我们执行了和前面示例中类似的 Socket 连接和数据交换操作,并将结果显示在消息显示区域中。
在 `show()` 方法中,我们显示了窗口,而在 `main()` 方法中,我们创建了 `GUIExample` 的实例,并调用了它的 `show()` 方法来显示窗口。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)