import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class clientWindow {
static Text chatWindow;
public static void sendMessage(Socket socket, String message) throws IOException {
PrintWriter pr = new PrintWriter(socket.getOutputStream());
pr.println("Client: " + message);
pr.flush();
}
public static void main(String[] args) throws UnknownHostException, IOException {
Socket s = new Socket("10.0.1.8", 4500);
Display display = new Display();
Shell clientWindow = new Shell(display);
GridLayout layout = new GridLayout();
layout.numColumns = 1;
clientWindow.setLayout(layout);
GridData data = new GridData(GridData.FILL_HORIZONTAL);
GridData data1 = new GridData(GridData.FILL_BOTH);
chatWindow = new Text(clientWindow, SWT.MULTI | SWT.V_SCROLL | SWT.READ_ONLY);
chatWindow.setLayoutData(data1);
Text messageBox = new Text(clientWindow, SWT.SINGLE);
messageBox.setLayoutData(data);
Button send = new Button(clientWindow, 0);
send.setText("Send");
send.addSelectionListener(new SelectionListener() {
public void widgetSelected(SelectionEvent event) {
try {
sendMessage(s, messageBox.getText());
messageBox.setText("");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void widgetDefaultSelected(SelectionEvent arg0) {
// TODO Auto-generated method stub
}
});
clientWindow.open();
while (!clientWindow.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
}
这是我完成的一个小型消息传递应用程序。此处的所有内容在Eclipse中都可以正常工作。但是,当我尝试在终端中运行它时,我得到了。
Exception in thread "main" org.eclipse.swt.SWTException: Invalid thread access
at org.eclipse.swt.SWT.error(SWT.java:4711)
at org.eclipse.swt.SWT.error(SWT.java:4626)
at org.eclipse.swt.SWT.error(SWT.java:4597)
at org.eclipse.swt.widgets.Display.error(Display.java:1112)
at org.eclipse.swt.widgets.Display.createDisplay(Display.java:853)
at org.eclipse.swt.widgets.Display.create(Display.java:837)
at org.eclipse.swt.graphics.Device.<init>(Device.java:132)
at org.eclipse.swt.widgets.Display.<init>(Display.java:736)
at org.eclipse.swt.widgets.Display.<init>(Display.java:727)
at clientWindow.main(clientWindow.java:28)
我很确定当尝试从不在“ main”中的内容访问Display时会发生此错误,这不是我要执行的操作。那为什么给我这个错误呢?
答案 0 :(得分:0)
从Display
代码中的行号来看,您正在macOS上运行此代码。
在macOS上,在终端中使用-XstartOnFirstThread
命令运行代码时,必须指定java
选项。
该程序可在Eclipse中运行,因为Eclipse会在“运行配置”中自动为您进行设置。