启动套接字服务器时 JFrame 显示为空

发布于 2025-01-10 14:20:01 字数 5258 浏览 0 评论 0原文

当代码使用套接字时,接收帧加载为空。 它不会添加 fileNameLabelheaderLabelscrollFile,如果我删除套接字,那么它会加载所有添加的 Swing 组件。

我该如何处理?

这是接收文件的完整代码:

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
// import java.lang.module.ModuleDescriptor.Builder;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

// import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

// import javax.swing.border.Border;
// import javax.swing.border.EmptyBorder;
// import java.awt.Color;
import java.awt.Component;

class App {

    public static File[] file = new File[1];

    public static void receiveFile() {

        JFrame receiveFileFrame;
        JPanel receiveFilePanel;
        JLabel fileNameLabel, headerLabel;

        receiveFileFrame = new JFrame();
        receiveFilePanel = new JPanel();
        fileNameLabel = new JLabel();
        headerLabel = new JLabel();

        receiveFileFrame.setBounds(750, 300, 400, 400);
        receiveFileFrame.setLayout(new BoxLayout(receiveFileFrame.getContentPane(), BoxLayout.Y_AXIS));

        JScrollPane scrollFiles = new JScrollPane(receiveFilePanel);
        scrollFiles.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        fileNameLabel.setFont(new Font("Serif", Font.BOLD, 20));
        fileNameLabel.setAlignmentX(Component.CENTER_ALIGNMENT);

        headerLabel.setText("Received Files");
        headerLabel.setFont(new Font("Serif", Font.BOLD, 20));
        headerLabel.setAlignmentX(Component.CENTER_ALIGNMENT);

        receiveFilePanel.add(fileNameLabel);

        receiveFileFrame.add(headerLabel);
        receiveFileFrame.add(scrollFiles);

        receiveFileFrame.setVisible(true);

        receiveFileFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        try {

            ServerSocket serverSocket = new ServerSocket(4444);
            while (true) {
                Socket socket = serverSocket.accept();
                DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
                int fileNameLength = dataInputStream.readInt();
                byte[] fileNameSize = new byte[fileNameLength];
                dataInputStream.readFully(fileNameSize, 0, fileNameSize.length);
                String fileName = new String(fileNameSize);
                fileNameLabel.setText(fileName);
                int fileContentLength = dataInputStream.readInt();
                byte[] fileContentSize = new byte[fileContentLength];
                dataInputStream.readFully(fileContentSize, 0, fileContentLength);
                File fileDownload = new File(fileName);
                FileOutputStream fileOutputStream = new FileOutputStream(fileDownload);
                fileOutputStream.write(fileContentSize);
                fileOutputStream.close();
            }
            
        } catch (Exception e) {
            JOptionPane.showMessageDialog(receiveFileFrame, e, "Message", 0);
        }

    }

    public static void main(String[] args) throws Exception {
        JFrame mainFrame = new JFrame();
        JButton send, receive;
        JPanel mainPanel, buttoPanel;
        JLabel heading;
        // Border border = BorderFactory.createLineBorder(Color.black);

        heading = new JLabel();
        send = new JButton();
        receive = new JButton();
        mainPanel = new JPanel();
        buttoPanel = new JPanel();

        mainFrame.setBounds(700, 250, 400, 200);
        mainFrame.setLayout(new BoxLayout(mainFrame.getContentPane(), BoxLayout.Y_AXIS));

        heading.setText("File Transfer");
        heading.setFont(new Font("Serif", Font.BOLD, 20));
        heading.setAlignmentX(Component.CENTER_ALIGNMENT);

        send.setText("Send");
        send.setSize(100, 50);
        send.setFont(new Font("Serif", Font.PLAIN, 15));

        receive.setText("Receive");
        receive.setSize(100, 50);
        receive.setFont(new Font("Serif", Font.PLAIN, 15));

        buttoPanel.add(send);
        buttoPanel.add(receive);

        mainPanel.add(heading);
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
        mainPanel.add(Box.createHorizontalStrut(10));
        mainPanel.add(buttoPanel);

        mainFrame.add(mainPanel);

        mainFrame.setVisible(true);
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        send.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                JOptionPane.showMessageDialog(mainFrame, "Send feature not added", "Message", 0);

            }
        });

        receive.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                receiveFile();

            }
        });
    }
}

When the code uses a socket, the receiving frame loads empty.
It does not add fileNameLabel, headerLabel or scrollFile and if I remove the socket then it loads all added Swing components.

How can I deal with it?

This is the full code of receive files:

import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
// import java.lang.module.ModuleDescriptor.Builder;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

// import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

// import javax.swing.border.Border;
// import javax.swing.border.EmptyBorder;
// import java.awt.Color;
import java.awt.Component;

class App {

    public static File[] file = new File[1];

    public static void receiveFile() {

        JFrame receiveFileFrame;
        JPanel receiveFilePanel;
        JLabel fileNameLabel, headerLabel;

        receiveFileFrame = new JFrame();
        receiveFilePanel = new JPanel();
        fileNameLabel = new JLabel();
        headerLabel = new JLabel();

        receiveFileFrame.setBounds(750, 300, 400, 400);
        receiveFileFrame.setLayout(new BoxLayout(receiveFileFrame.getContentPane(), BoxLayout.Y_AXIS));

        JScrollPane scrollFiles = new JScrollPane(receiveFilePanel);
        scrollFiles.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        fileNameLabel.setFont(new Font("Serif", Font.BOLD, 20));
        fileNameLabel.setAlignmentX(Component.CENTER_ALIGNMENT);

        headerLabel.setText("Received Files");
        headerLabel.setFont(new Font("Serif", Font.BOLD, 20));
        headerLabel.setAlignmentX(Component.CENTER_ALIGNMENT);

        receiveFilePanel.add(fileNameLabel);

        receiveFileFrame.add(headerLabel);
        receiveFileFrame.add(scrollFiles);

        receiveFileFrame.setVisible(true);

        receiveFileFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        try {

            ServerSocket serverSocket = new ServerSocket(4444);
            while (true) {
                Socket socket = serverSocket.accept();
                DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
                int fileNameLength = dataInputStream.readInt();
                byte[] fileNameSize = new byte[fileNameLength];
                dataInputStream.readFully(fileNameSize, 0, fileNameSize.length);
                String fileName = new String(fileNameSize);
                fileNameLabel.setText(fileName);
                int fileContentLength = dataInputStream.readInt();
                byte[] fileContentSize = new byte[fileContentLength];
                dataInputStream.readFully(fileContentSize, 0, fileContentLength);
                File fileDownload = new File(fileName);
                FileOutputStream fileOutputStream = new FileOutputStream(fileDownload);
                fileOutputStream.write(fileContentSize);
                fileOutputStream.close();
            }
            
        } catch (Exception e) {
            JOptionPane.showMessageDialog(receiveFileFrame, e, "Message", 0);
        }

    }

    public static void main(String[] args) throws Exception {
        JFrame mainFrame = new JFrame();
        JButton send, receive;
        JPanel mainPanel, buttoPanel;
        JLabel heading;
        // Border border = BorderFactory.createLineBorder(Color.black);

        heading = new JLabel();
        send = new JButton();
        receive = new JButton();
        mainPanel = new JPanel();
        buttoPanel = new JPanel();

        mainFrame.setBounds(700, 250, 400, 200);
        mainFrame.setLayout(new BoxLayout(mainFrame.getContentPane(), BoxLayout.Y_AXIS));

        heading.setText("File Transfer");
        heading.setFont(new Font("Serif", Font.BOLD, 20));
        heading.setAlignmentX(Component.CENTER_ALIGNMENT);

        send.setText("Send");
        send.setSize(100, 50);
        send.setFont(new Font("Serif", Font.PLAIN, 15));

        receive.setText("Receive");
        receive.setSize(100, 50);
        receive.setFont(new Font("Serif", Font.PLAIN, 15));

        buttoPanel.add(send);
        buttoPanel.add(receive);

        mainPanel.add(heading);
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
        mainPanel.add(Box.createHorizontalStrut(10));
        mainPanel.add(buttoPanel);

        mainFrame.add(mainPanel);

        mainFrame.setVisible(true);
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        send.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                JOptionPane.showMessageDialog(mainFrame, "Send feature not added", "Message", 0);

            }
        });

        receive.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {

                receiveFile();

            }
        });
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爱给你人给你 2025-01-17 14:20:01

您正在 事件调度上调用方法 receiveFile主题(美国东部时间)。方法 receiveFile 包含以下行:

Socket socket = serverSocket.accept();

这是来自 accept 方法的javadoc

该方法会阻塞,直到建立连接为止。

换句话说,当您运行程序时,其执行将停止在上面一行,直到建立套接字连接。这样你就真的停止了 EDT。如果 EDT 停止,那么它就无法绘制任何东西,这就是为什么

它不添加 fileNameLabelheaderLabelscrollFile

这也是为什么

如果我删除套接字,那么它会加载所有添加的 Swing 组件

。您需要在单独的线程上运行套接字代码。
您可以使用 SwingWorker 或创建一个新的 Thread 运行您的套接字代码并通过调用方法 invokeLater。请注意,您可能会发现很多使用 javax.swing.SwingUtilities 类的 invokeLater 方法的示例。该方法只是调用类 java.awt.EventQueue 中的同名方法。

You are calling method receiveFile on the Event Dispatch Thread (EDT). Method receiveFile contains the following line:

Socket socket = serverSocket.accept();

Here is a quote from the javadoc of method accept:

The method blocks until a connection is made.

In other words, when you run your program, its execution will stop at the above line until a socket connection is made. Thus you have literally stopped the EDT. If the EDT is stopped then it can't paint anything and that's why

It does not add fileNameLabel, headerLabel or scrollFile

And that's also why

if I remove the socket then it loads all added Swing components

You need to run your socket code on a separate thread.
You can either use a SwingWorker or create a new Thread to run your socket code and update the GUI from that thread by calling method invokeLater of class java.awt.EventQueue. Note that you will probably find a lot of examples that use method invokeLater of class javax.swing.SwingUtilities. That method simply calls the same name method in class java.awt.EventQueue.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文