首页 > 解决方案 > 从 MainGUI 类调用另一个类中的 GUI,但得到空白白框

问题描述

如果这个问题已经解决了,我很抱歉,因为我搜索了很多东西但无法解决我的问题。问题是,我为 MainGUI 类制作了一个 GUI,并想从另一个类访问另一个 GUI,比如 ClientGUI 或 ServerGUI,但我一直收到空白白框(尽管连接状态将被连接/正常运行)

MainGUI.java

package chat
/*
 * Notes: This project use source code by Ashish Myles: 
 * https://ashishmyles.com/tutorials/tcpchat/index.html
 */

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.border.EmptyBorder;

public class MainGUI 
{
    public MainGUI() 
    {
        JFrame mainFrame = new JFrame("ServerClient Chat");
        JPanel mainPanel = new JPanel();
        BoxLayout mainLayout = new BoxLayout(mainPanel, BoxLayout.Y_AXIS);

        Font commonFont = new Font("Tahoma", Font.PLAIN, 14);

        mainPanel.setLayout(mainLayout);
        mainPanel.setBorder(new EmptyBorder(new Insets(120, 0, 0, 0)));

        JLabel titleLabel = new JLabel("ServerClient Chat");
        titleLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        titleLabel.setFont(new Font("Courier", Font.BOLD, 20));

        JPanel ipPane = new JPanel();
        ipPane.setLayout(new FlowLayout());
        ipPane.setMinimumSize(new Dimension(300, 70));
        ipPane.setMaximumSize(new Dimension(300, 70));
        ipPane.setPreferredSize(new Dimension(300, 70));

        String myIp = "";
        ipcheck checkIp = new ipcheck();

        try 
        {
            myIp = checkIp.ip();
        } 

        catch (Exception e) 
        {
            e.printStackTrace();
        }

        JLabel ipLabel = new JLabel("Your IP address is ");
        ipLabel.setFont(commonFont);

        JLabel ipAddress = new JLabel(myIp);
        ipAddress.setFont(new Font("Tahoma", Font.BOLD, 15));

        ipPane.add(ipLabel);
        ipPane.add(ipAddress);

        JLabel logLabel = new JLabel("Log me in as: ");
        logLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
        logLabel.setFont(commonFont);

        JPanel userPane = new JPanel();
        userPane.setLayout(new FlowLayout(FlowLayout.TRAILING));
        userPane.setMinimumSize(new Dimension(150, 40));
        userPane.setMaximumSize(new Dimension(150, 40));
        userPane.setPreferredSize(new Dimension(150, 40));

        JRadioButton clientButton = new JRadioButton("Client");
        JRadioButton serverButton = new JRadioButton("Server");

        ButtonGroup userButton = new ButtonGroup();
        userButton.add(clientButton);
        userButton.add(serverButton);

        userPane.add(clientButton);
        userPane.add(serverButton);

        JButton selectButton = new JButton("Select");
        selectButton.setAlignmentX(Component.CENTER_ALIGNMENT);
        selectButton.setFont(commonFont);

        selectButton.addActionListener(new ActionListener() 
        {
            @Override
            public void actionPerformed(ActionEvent e) 
            {       
                if(clientButton.isSelected()) 
                {   
                    // ask for username, ip address & port number input
                    String ip, port;
                    ip = JOptionPane.showInputDialog(mainFrame, "Input server's IP address", "Input IP address", JOptionPane.OK_CANCEL_OPTION);
                    port = JOptionPane.showInputDialog(mainFrame, "Input server's port number", "Input port number", JOptionPane.OK_CANCEL_OPTION);

                    String ipAddress = ip.toString();
                    int portNum = Integer.parseInt(port);

                    JOptionPane.showConfirmDialog(mainFrame, "You are now connected to Server\nIP Address     :   " + ipAddress + "\nPort Number  :   " + portNum, "Connected", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE);

                    // open ClientGUI interface
                    new ClientGUI(ipAddress, portNum);

                    mainFrame.setVisible(false);
                } 

                else if(serverButton.isSelected()) 
                {   
                    // ask for port number input
                    String port;
                    String myIp = "";
                    ipcheck checkIp = new ipcheck();

                    try 
                    {
                        myIp = checkIp.ip();
                    } 

                    catch (Exception ee) 
                    {
                        ee.printStackTrace();
                    }

                    port = JOptionPane.showInputDialog(mainFrame, "Input server's port number", "Input port number", JOptionPane.OK_CANCEL_OPTION);

                    int portNum = Integer.parseInt(port);

                    JOptionPane.showConfirmDialog(mainFrame, "You are accepting connection from Client\nIP Address     :   " + myIp + "\nPort Number  :   " + portNum, "Connected", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE);

                    // open ServerGUI interface
                    new ServerGUI(portNum);
                    mainFrame.setVisible(false);
                }
            }
        });

        mainPanel.add(titleLabel);
        mainPanel.add(Box.createRigidArea(new Dimension(0, 20)));
        mainPanel.add(ipPane);
        mainPanel.add(Box.createRigidArea(new Dimension(0, 60)));
        mainPanel.add(logLabel);
        mainPanel.add(Box.createRigidArea(new Dimension(0, 5)));
        mainPanel.add(userPane);
        mainPanel.add(Box.createRigidArea(new Dimension(0, 5)));
        mainPanel.add(selectButton);

        mainFrame.add(mainPanel);

        mainPanel.setBackground(Color.LIGHT_GRAY);
        ipPane.setBackground(Color.LIGHT_GRAY);
        userPane.setBackground(Color.LIGHT_GRAY);
        clientButton.setBackground(Color.LIGHT_GRAY);
        serverButton.setBackground(Color.LIGHT_GRAY);

        mainFrame.setSize(700, 500);
        mainFrame.setResizable(false);
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainFrame.setLocationRelativeTo(null);
        mainFrame.setVisible(true);
    }

    public static void main(String[] args)
    {
        new MainGUI();
    }
}

服务器GUI.java

package chat;
/*
 * Notes: This project use source code by Ashish Myles: 
 * https://ashishmyles.com/tutorials/tcpchat/index.html
 */

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

public class ServerGUI implements Runnable 
{
    // Connect status constants
    public final static int NULL = 0;
    public final static int DISCONNECTED = 1;
    public final static int DISCONNECTING = 2;
    public final static int BEGIN_CONNECT = 3;
    public final static int CONNECTED = 4;

    // Other constants
    public final static String statusMessages[] = 
        {
            " Error! Could not connect!", " Disconnected",
            " Disconnecting...", " Connecting...", " Connected"
        };
    public final static ServerGUI tcpObj = new ServerGUI();
    public final static String END_CHAT_SESSION = new Character((char)0).toString(); // Indicates the end of a session
    public static Font commonFont = new Font("Tahoma", Font.PLAIN, 14);

    // Connection state info
    public static String hostIP = "localhost";
    public static int port = 1700;
    public static int connectionStatus = DISCONNECTED;
    public static boolean isHost = true;
    public static String statusString = statusMessages[connectionStatus];
    public static StringBuffer toAppend = new StringBuffer("");
    public static StringBuffer toSend = new StringBuffer("");

    // Various GUI components and info
    public static JFrame mainFrame = null;
    public static JTextArea messageBox = null;
    public static JPanel statusBar = null;
    public static JLabel statusField = null;
    public static JLabel status = null;
    public static JLabel statusLabel = null;
    public static JTextField statusColor = null;
    public static JButton homeButton = null;
    public static JButton disconnectButton = null;
    public static JButton sendButton = null;
    public static JButton replyButton = null;

    // TCP Components
    public static ServerSocket hostServer = null;
    public static Socket socket = null;
    public static BufferedReader in = null;
    public static PrintWriter out = null;

    // Initialize all the GUI components and display the frame
    private static void initGUI() 
    {   
        // Set up the status bar
        statusField = new JLabel();
        statusField.setText(statusMessages[DISCONNECTED]);
        statusColor = new JTextField(1);
        statusColor.setBackground(Color.red);
        statusColor.setEditable(false);
        statusBar = new JPanel(new BorderLayout());
        statusBar.add(statusColor, BorderLayout.WEST);
        statusBar.add(statusField, BorderLayout.CENTER);

        // First Panel
        homeButton = new JButton("Home");
        disconnectButton = new JButton("Disconnect");

        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

        JPanel firstPanel = new JPanel();
        firstPanel.setLayout(new BoxLayout(firstPanel, BoxLayout.X_AXIS));

        JPanel topLeftPanel = new JPanel();
        topLeftPanel.setLayout(new BoxLayout(topLeftPanel, BoxLayout.X_AXIS));

        statusLabel = new JLabel("Status: ");
        status = new JLabel("");

        statusLabel.setFont(commonFont);
        status.setFont(commonFont);

        topLeftPanel.add(statusLabel);
        topLeftPanel.add(status);
        topLeftPanel.add(Box.createRigidArea(new Dimension(2, 0)));

        JPanel topRightPanel = new JPanel();
        topRightPanel.setLayout(new BoxLayout(topRightPanel, BoxLayout.Y_AXIS));

        topRightPanel.add(Box.createRigidArea(new Dimension(0, 40)));
        topRightPanel.add(disconnectButton);
        topRightPanel.add(Box.createRigidArea(new Dimension(0, 10)));
        topRightPanel.add(homeButton);


        firstPanel.add(topLeftPanel);
        firstPanel.add(Box.createRigidArea(new Dimension(390, 120)));
        firstPanel.add(topRightPanel);

        // Second Panel

        sendButton = new JButton("Send");
        replyButton = new JButton("Reply");

        JPanel secondPanel = new JPanel();
        secondPanel.setLayout(new BoxLayout(secondPanel, BoxLayout.X_AXIS));
        secondPanel.setAlignmentY(Component.TOP_ALIGNMENT);

        sendButton.setPreferredSize(new Dimension(300,50));
        replyButton.setPreferredSize(new Dimension(300,50));

        secondPanel.add(sendButton);
        secondPanel.add(Box.createRigidArea(new Dimension(15, 0)));
        secondPanel.add(replyButton);
        secondPanel.add(Box.createRigidArea(new Dimension(450, 0)));

        // Third Panel
        JPanel thirdPanel = new JPanel(new BorderLayout());
        messageBox = new JTextArea();
//      messageBox.setLineWrap(true);
        messageBox.setEditable(false);

        JScrollPane textBox = new JScrollPane(messageBox, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        textBox.setPreferredSize(new Dimension(700, 400));

        thirdPanel.add(textBox, BorderLayout.NORTH);
        thirdPanel.add(statusBar, BorderLayout.SOUTH);          

        mainPanel.add(firstPanel);
        mainPanel.add(Box.createRigidArea(new Dimension(100, 0)));
        mainPanel.add(secondPanel);
        mainPanel.add(Box.createRigidArea(new Dimension(500, 10)));
        mainPanel.add(thirdPanel);

        mainPanel.setBackground(Color.LIGHT_GRAY);
        firstPanel.setBackground(Color.LIGHT_GRAY);
        secondPanel.setBackground(Color.LIGHT_GRAY);
        thirdPanel.setBackground(Color.LIGHT_GRAY);
        topLeftPanel.setBackground(Color.LIGHT_GRAY);
        topRightPanel.setBackground(Color.LIGHT_GRAY);

        sendButton.addActionListener(new ActionListener() 
        {   
            @Override
            public void actionPerformed(ActionEvent arg0) 
            {
                JFrame createFrame = new JFrame("Input message");

                JPanel createPanel = new JPanel();

                createPanel.add(Box.createRigidArea(new Dimension(0, 20)));

                JLabel createLabel = new JLabel("Input message: ");
                createPanel.add(createLabel);

                createPanel.add(Box.createRigidArea(new Dimension(0, 50)));

                JTextArea textInput = new JTextArea();
                textInput.setMinimumSize(new Dimension(600, 250));
                textInput.setMaximumSize(new Dimension(600, 250));
                textInput.setPreferredSize(new Dimension(600, 250));

                createPanel.add(textInput);

                JPanel buttonPanel = new JPanel();

                JButton sendButton = new JButton("Send");
                JButton cancelButton = new JButton("Cancel");

                sendButton.addActionListener(new ActionListener() 
                {   
                    @Override
                    public void actionPerformed(ActionEvent e) 
                    {
                        String s = textInput.getText();
                        if (!s.equals("")) 
                        {
                            appendToChatBox("Server: " + s + "\n");
                            textInput.selectAll();

                            // Send the string
                            sendString(s);
                        }

                        createFrame.dispose();
                    }
                });

                cancelButton.addActionListener(new ActionListener() {

                    @Override
                    public void actionPerformed(ActionEvent e) {
                        createFrame.dispose();
                    }
                });

                buttonPanel.add(sendButton);
                buttonPanel.add(Box.createRigidArea(new Dimension(5, 0)));
                buttonPanel.add(cancelButton);

                createPanel.add(buttonPanel);

                createFrame.add(createPanel);

                buttonPanel.setBackground(Color.LIGHT_GRAY);
                createPanel.setBackground(Color.LIGHT_GRAY);
                createFrame.setSize(700, 400);
                createFrame.setResizable(false);
                createFrame.setVisible(true);
                createFrame.setLocationRelativeTo(mainFrame);
            }
        });

        replyButton.addActionListener(new ActionListener() 
        {   
            @Override
            public void actionPerformed(ActionEvent e) 
            {

            }
        });

        disconnectButton.addActionListener(new ActionListener() 
        {   
            @Override
            public void actionPerformed(ActionEvent e) 
            {
                int option = JOptionPane.showConfirmDialog(mainFrame, "Do you want to disconnect?", "Disconnect", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE);

                if(option == JOptionPane.OK_OPTION)
                {
                    changeStatusNTS(DISCONNECTING, true);
                }

                else
                    return;
            }
        });

        homeButton.addActionListener(new ActionListener() 
        {   
            @Override
            public void actionPerformed(ActionEvent e) 
            {
                new MainGUI();
                mainFrame.dispose();            
                return;
            }
        });

        // Set up the main frame
        mainFrame = new JFrame("Server");
        mainFrame.add(mainPanel);
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//      mainFrame.setContentPane(mainPane);
        mainFrame.setResizable(false);
        mainFrame.setSize(800,630); // 800,650
        mainFrame.setLocationRelativeTo(null);
        mainFrame.setVisible(true);
    }

    // The thread-safe way to change the GUI components while
    // changing state
    private static void changeStatusTS(int newConnectStatus, boolean noError) 
    {
        // Change state if valid state
        if (newConnectStatus != NULL) 
        {
            connectionStatus = newConnectStatus;
        }

        // If there is no error, display the appropriate status message
        if (noError) 
        {
            statusString = statusMessages[connectionStatus];
        }

        // Otherwise, display error message
        else 
        {
            statusString = statusMessages[NULL];
        }

        // Call the run() routine (Runnable interface) on the
        // error-handling and GUI-update thread
        SwingUtilities.invokeLater(tcpObj);
    }

    // The non-thread-safe way to change the GUI components while
    // changing state
    private static void changeStatusNTS(int newConnectStatus, boolean noError) 
    {
        // Change state if valid state
        if (newConnectStatus != NULL) 
        {
            connectionStatus = newConnectStatus;
        }

        // If there is no error, display the appropriate status message
        if (noError) 
        {
            statusString = statusMessages[connectionStatus];
        }

        // Otherwise, display error message
        else 
        {
            statusString = statusMessages[NULL];
        }

        // Call the run() routine (Runnable interface) on the
        // current thread
        tcpObj.run();
    }

    // Thread-safe way to append to the chat box
    private static void appendToChatBox(String s) 
    {
        synchronized (toAppend) 
        {
            toAppend.append(s);
        }
    }

    // Add text to send-buffer
    private static void sendString(String s) 
    {
        synchronized (toSend) 
        {
            toSend.append(s + "\n");
        }
    }

    // Cleanup for disconnect
    private static void cleanUp() 
    {
        try 
        {
            if (hostServer != null) 
            {
                hostServer.close();
                hostServer = null;
            }
        }

        catch (IOException e) { hostServer = null; }

        try 
        {
            if (socket != null) 
            {
                socket.close();
                socket = null;
            }
        }

        catch (IOException e) { socket = null; }

        try 
        {
            if (in != null) 
            {
                in.close();
                in = null;
            }
        }

        catch (IOException e) { in = null; }

        if (out != null) 
        {
            out.close();
            out = null;
        }
    }

    // Checks the current state and sets the enables/disables
    // accordingly
    @Override
    public void run() 
    {
        switch (connectionStatus) 
        {
            case DISCONNECTED:
                homeButton.setEnabled(true);
                disconnectButton.setEnabled(false);
                sendButton.setEnabled(false);
                replyButton.setEnabled(false);
                status.setText("Disconnected");
                status.setFont(new Font("Tahoma", Font.BOLD, 14));
                statusColor.setBackground(Color.red);
                break;

            case DISCONNECTING:
                homeButton.setEnabled(false);
                disconnectButton.setEnabled(false);
                sendButton.setEnabled(false);
                replyButton.setEnabled(false);
                status.setText("Disconnecting...");
                status.setFont(new Font("Tahoma", Font.BOLD, 14));
                statusColor.setBackground(Color.orange);
                break;

            case CONNECTED:
                homeButton.setEnabled(false);
                disconnectButton.setEnabled(true);
                sendButton.setEnabled(true);
                replyButton.setEnabled(true);
                status.setText("Connected");
                status.setFont(new Font("Tahoma", Font.BOLD, 14));
                statusColor.setBackground(Color.green);
                break;

            case BEGIN_CONNECT:
                homeButton.setEnabled(false);
                disconnectButton.setEnabled(false);
                sendButton.setEnabled(true);
                replyButton.setEnabled(true);
                status.setText("Connecting...");
                status.setFont(new Font("Tahoma", Font.BOLD, 14));
                statusColor.setBackground(Color.orange);
                break;
        }

        // Make sure that the button/text field states are consistent
        // with the internal states
        statusField.setText(statusString);
        messageBox.append(toAppend.toString());
        toAppend.setLength(0);

        mainFrame.repaint();
    }

    public ServerGUI(int portNum)
    {
        String s;

        initGUI();

        changeStatusNTS(BEGIN_CONNECT, true);

        while (true) 
        {
            try 
            { 
                // Poll every ~10 ms
                Thread.sleep(10);
            }

            catch (InterruptedException e) {}

            switch (connectionStatus) 
            {
                case BEGIN_CONNECT:
                    try 
                    {
                        hostServer = new ServerSocket(portNum);
                        socket = hostServer.accept();

                        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                        out = new PrintWriter(socket.getOutputStream(), true);
                        changeStatusTS(CONNECTED, true);
                    }

                    // If error, clean up and output an error message
                    catch (IOException e) 
                    {
                        cleanUp();
                        changeStatusTS(DISCONNECTED, false);
                    }

                    break;

                case CONNECTED:
                    try 
                    {
                        // Send data
                        if (toSend.length() != 0) 
                        {
                            out.print(toSend); out.flush();
                            toSend.setLength(0);
                            changeStatusTS(NULL, true);
                        }

                        // Receive data
                        if (in.ready()) 
                        {
                            s = in.readLine();
                            if ((s != null) &&  (s.length() != 0)) 
                            {
                                // Check if it is the end of a transmission
                                if (s.equals(END_CHAT_SESSION)) 
                                {
                                    changeStatusTS(DISCONNECTING, true);
                                }

                                // Otherwise, receive what text
                                else 
                                {
                                    appendToChatBox("Client: " + s + "\n");
                                    changeStatusTS(NULL, true);
                                }
                            }
                        }
                    }

                    catch (IOException e) 
                    {   
                        cleanUp();
                        changeStatusTS(DISCONNECTED, false);
                    }

                    break;

                case DISCONNECTING:
                    // Tell other chatter to disconnect as well
                    out.print(END_CHAT_SESSION); out.flush();

                    // Clean up (close all streams/sockets)
                    cleanUp();
                    changeStatusTS(DISCONNECTED, true);
                    break;

                default: break; // do nothing
            }
        }
    }

    public ServerGUI()
    {
        // TODO Auto-generated constructor stub
    }
}

ipcheck.java(用于检查 IP 地址)

package chat;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class ipcheck {

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

    public String ip() throws Exception
    {
        String ip;

        InetAddress localhost = InetAddress.getLocalHost(); 
        ip = localhost.getHostAddress().trim();

        return ip;
    }
}

我跳过了 ClientGUI,因为它与 ServerGUI 相同,只是在 CONNECT 的情况下更改了套接字。

请帮我解决在MainGUI中使用选择按钮调用ServerGUI时显示的空白白框,谢谢:)

标签: javaeclipse

解决方案


推荐阅读