我正在创建一个TCP服务器/客户端系统。目前,我已经创建了一个ConnectionFrame.java
文件,包括一个带有JFrame
,JButton
和JTextArea
的JTextField
。启动客户端时,我希望此JFrame
出现(因此,当我启动client.jar时,也应执行ConnectionFrame
。
我以为可以通过将以下行放入客户端主方法来做到这一点:
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();
}
}
最佳答案
您需要像这样安排event-dispatching thread
的创建任务:
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
ConnectionFrame();
}
}
);
在Java 8中它将是:
SwingUtilities.invokeLater(ConnectionFrame::ConnectionFrame);