我制作了一个消息传递程序,其中客户端具有GUI。在启动客户端之前,客户端程序需要有关用户和服务器的信息。我使用args数组通过命令行输入了信息。
但是,现在程序正常运行了,我制作了一个用于输入信息的GUI。我在另一个类中进行了调用,该类调用客户端类并将信息传递给客户端类。信息GUI可以正常工作,但是当我输入信息并调用客户端类时,框架会显示出来,但是框架中没有任何组件可见。
当我恢复为旧方法时,客户端GUI可以正常工作。我不知道该怎么办。
调用客户端类的代码:
btn.addActionListener(new ActionListener() {
...
username = Username.getText();
hostName = sa.getText();
portNr = Integer.parseInt(spnr.getText());
f.dispose();
System.out.println("frame disposed of");
try {
Client client = new Client();
f.dispose();
Client.llc(username, hostName, portNr);
} catch (IOException e) {
e.printStackTrace();
}
}
});
客户端代码:
public static void llc(String iun, String ihn, int ipnr) throws IOException {
username = iun;
hostName = ihn;
portNr = ipnr;
launchClient();
}
public static void launchClient() throws IOException {
try (
//socket setup
Socket socket = new Socket(hostName, portNr);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
) {
System.out.println("opened streams");
//frame setup
JFrame frame = new JFrame("frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//text field
JTextField MSGText = new JTextField(5);
//text area
JTextArea MSGD = new JTextArea(20, 30);
MSGD.setEditable(false);
JScrollPane scrollPane = new JScrollPane(MSGD);
System.out.println("opened streams");
//button
JButton b = new JButton("Send message");
b.setPreferredSize(new Dimension(60, 30));
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
sendMSG = MSGText.getText();
MSGText.setText("");
out.println("<" + username + ">: " + sendMSG);
}
});
//panel
JPanel p = new JPanel();
p.setLayout(new BoxLayout(p, BoxLayout.PAGE_AXIS));
p.add(Box.createVerticalStrut(5));
p.add(scrollPane);
p.add(Box.createVerticalStrut(5));
p.add(MSGText);
p.add(Box.createVerticalStrut(5));
p.add(b);
p.add(Box.createVerticalStrut(5));
JPanel pMain = new JPanel();
pMain.setLayout(new BoxLayout(pMain, BoxLayout.LINE_AXIS));
pMain.add(Box.createHorizontalStrut(5));
pMain.add(p);
pMain.add(Box.createHorizontalStrut(5));
frame.getContentPane().add(pMain);
//frame visiblity
frame.pack();
frame.setVisible(true);
System.out.println("opened streams");
while((getMSG = in.readLine()) != null) {
MSGD.append(getMSG + "\n");
System.out.println("opened streams");
}
}
}
答案 0 :(得分:-1)
如果您的客户端代码是扩展JFrame的Client类,则Frame可能在组件之前进行初始化。要解决此问题,您只需将JFrame成员设置为客户端类中的public全局变量,然后在调用llc之后调用client.frame.repaint()。
public class Client extends JFrame {
public JFrame frame;
//everything else the same
}
-----------------------------------
btn.addActionListener(new ActionListener() {
...
username = Username.getText();
hostName = sa.getText();
portNr = Integer.parseInt(spnr.getText());
f.dispose();
System.out.println("frame disposed of");
try {
Client client = new Client();
f.dispose();
Client.llc(username, hostName, portNr);
client.frame.repaint();
} catch (IOException e) {
e.printStackTrace();
}
}
});