我正在创建TCP服务器/客户端系统。目前,我已创建了ConnectionFrame.java
个文件,其中包含JFrame
个JButton
,JTextArea
和JTextField
。启动我的客户端时,我希望显示此JFrame
(因此,当我启动client.jar时,ConnectionFrame
也应该执行。
我假设我可以通过将以下行添加到客户端main方法中来完成此操作:
ConnectionFrame cf = new ConnectionFrame();
但没有运气。另一个尝试是写作:
ConnectionFrame.main(argv);
由于某种原因,似乎搞砸了我的原始代码。
编辑:为上下文添加代码
ConnectionFrame:
public class ConnectionFrame extends JFrame implements ActionListener {
JButton buttonLayout = new JButton("Connect to server");
JTextField textFieldLayout = new JTextField(1);
JTextArea consoleOutput = new JTextArea(1,20);
public void addComponentToPane(Container pane) {
buttonLayout.addActionListener(this);
textFieldLayout.setHorizontalAlignment(JTextField.CENTER);
consoleOutput.setEditable(false);
pane.add(buttonLayout, BorderLayout.PAGE_START);
pane.add(textFieldLayout, BorderLayout.CENTER);
pane.add(consoleOutput, BorderLayout.PAGE_END);
}
public static void ConnectionFrame() {
ConnectionFrame frame = new ConnectionFrame();
frame.addComponentToPane(frame.getContentPane());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if("Connect to server".equals(e.getActionCommand())){
consoleOutput.append("CONSOLE: Triggered");
}
}
public static void main(String[] args) {
ConnectionFrame();
}
}
客户:
public class TCPClient {
public static void main(String argv[]) throws Exception {
ConnectionFrame cf = new ConnectionFrame();
String sentence;
String modifiedSentence;
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
Socket clientSocket = new Socket("localhost", 54343);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
CanvasFrame myFrame = new CanvasFrame();
myFrame.setVisible(true);
ArrayList<Point> points = myFrame.location;
outToServer.writeInt(points.size());
for(Point p : points)
{
outToServer.writeInt(p.x);
outToServer.writeInt(p.y);
}
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentence = inFromUser.readLine();
outToServer.writeBytes(sentence + '\n');
modifiedSentence = inFromServer.readLine();
System.out.println("FROM SERVER: " + modifiedSentence);
clientSocket.close();
}
}
答案 0 :(得分:3)
您需要安排event-dispatching thread
的创建任务,如下所示:
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
ConnectionFrame();
}
}
);
在java 8中它将是:
SwingUtilities.invokeLater(ConnectionFrame::ConnectionFrame);