- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
import java.io.*;
import java.net.*;
import java.io.FileInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousCloseException;
import java.nio.channels.FileChannel;
class StreamCopier implements Runnable {
private InputStream in;
private BufferedOutputStream out;
public StreamCopier(InputStream in, BufferedOutputStream out)
{
this.in = in;
this.out = out;
}
public void run()
{
try
{
int n;
byte[] buffer = new byte[4096];
while ((n = in.read(buffer)) != -1)
{
out.write(buffer, 0, n);
out.flush();
}
}
catch (IOException e)
{
System.out.println(e);
}
}
}
class InputCopier implements Runnable
{
private BufferedInputStream in;
private OutputStream out;
public InputCopier(BufferedInputStream in, OutputStream out)
{
this.in = in;
this.out = out;
}
public void run()
{
try
{
int n;
byte buffer[] = new byte[4096];
while ((n = in.read(buffer)) != -1)
{
out.write(buffer, 0, n);
out.flush();
}
out.close();
}
catch (AsynchronousCloseException e)
{
}
catch (IOException e)
{
System.out.println(e);
}
}
}
public class Test
{
private static Socket socket;
public static void main(String[] args)throws IOException, InterruptedException, NoSuchFieldException, IllegalAccessException
{
try
{
ServerSocket serverSocket=new ServerSocket(5000);
socket=serverSocket.accept();
BufferedInputStream in=new BufferedInputStream(socket.getInputStream());
BufferedOutputStream out=new BufferedOutputStream(socket.getOutputStream());
// BufferedOutputStream err=new BufferedOutputStream(socket.getErrorStream());
Process process = Runtime.getRuntime().exec("java Hello");
Thread outThread = new Thread(new StreamCopier(process.getInputStream(), out));
outThread.start();
// Thread errThread = new Thread(new StreamCopier(process.getErrorStream(), err));
// errThread.start();
Thread inThread = new Thread(new InputCopier(in, process.getOutputStream()));
inThread.start();
process.waitFor();
System.in.close();
outThread.join();
// errThread.join();
inThread.join();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
socket.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
测试类包含服务器套接字程序
import java.io.*;
import java.net.*;
class User
{
private static Socket socket;
public static void main(String args[])
{
try
{
socket = new Socket("localhost",5000);
Thread t1 = new A(socket);
t1.start();
Thread t2 = new B(socket);
t2.start();
t1.join();
t2.join();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try
{
socket.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
class B extends Thread
{
Socket socket;
B(Socket socket)
{
this.socket=socket;
}
public void run()
{
try
{
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
InputStream in=System.in;
int n;
byte buffer[] = new byte[4096];
while ((n = in.read(buffer)) != -1)
{
out.write(buffer, 0, n);
out.flush();
}
}
catch(Exception e)
{}
}
}
class A extends Thread
{
Socket socket;
A(Socket socket)
{
this.socket=socket;
}
public void run()
{
try
{
BufferedInputStream in = new BufferedInputStream(socket.getInputStream());
OutputStream out = System.out;
int n;
byte[] buffer = new byte[4096];
while ((n = in.read(buffer)) != -1)
{
out.write(buffer, 0, n);
out.flush();
}
}
catch(Exception e)
{}
}
}
用户类包含客户端套接字程序。
程序的输出 Output of program
我想将进程的输出打印到 JTextArea 并通过 JTextField 将输入传递给进程。
用户界面代码。
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JButton;
public class Client {
private JFrame frame;
private JTextField textField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Client window = new Client();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Client() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JTextArea txtrTextAreaFor = new JTextArea();
txtrTextAreaFor.setText("Text Area For Output of process");
txtrTextAreaFor.setBounds(36, 11, 289, 143);
frame.getContentPane().add(txtrTextAreaFor);
textField = new JTextField();
textField.setBounds(36, 165, 191, 43);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnSubmit = new JButton("Submit");
btnSubmit.setBounds(236, 185, 89, 23);
frame.getContentPane().add(btnSubmit);
}
}
最佳答案
所以,我完全是凭空写出来的,没有经过测试,所以可能需要一些调整
Swing 是一个单线程框架,它也不是线程安全的。这意味着您不应该执行任何可能阻塞事件调度线程的操作,例如读取/写入Socket
,并且永远不应该从事件调度线程外部更新 UI。
看看Concurrency in Swing了解更多详情。
现在,对此的解决方案很少,最简单的可能是使用 SwingWorker
,它允许您在 EDT 之外在后台进行某种处理(长时间运行/阻塞)线程,但它提供了许多简单的方法将数据安全地同步回 UI。
参见Worker Threads and SwingWorker了解更多详情。
此示例对 WriteWorker
和 ReadWorker
使用 SwingWorker
,从技术上讲,您不需要使用 SwingWorker
用于写入操作,因为您并未真正与 UI 交互,但我这样做是因为它稍微简化了错误管理。
public class SocketThread implements Runnable {
private String host;
private int port;
private JTextArea ta;
private WriteWorker writeWorker;
private ReadWorker readWorker;
private CountDownLatch shutDownLatch;
public SocketThread(String host, int port, JTextArea ta) {
this.host = host;
this.port = port;
this.ta = ta;
}
public void write(String text) {
if (writeWorker != null) {
if (writeWorker.getState() == SwingWorker.StateValue.STARTED) {
writeWorker.write(text);
} else {
throw new IllegalStateException("Write worker is not running");
}
} else {
throw new NullPointerException("Write worker is nul");
}
}
public void close() {
if (writeWorker != null) {
writeWorker.cancel(true);
}
if (readWorker != null) {
readWorker.cancel(true);
}
// Force the CountDownLatch to release
if (shutDownLatch != null) {
shutDownLatch.countDown();
shutDownLatch.countDown();
}
}
@Override
public void run() {
try (Socket socket = new Socket(host, port)) {
writeWorker = new WriteWorker(socket.getOutputStream());
readWorker = new ReadWorker(socket.getInputStream(), ta);
writeWorker.addPropertyChangeListener(new PropertyChangeHandler());
readWorker.addPropertyChangeListener(new PropertyChangeHandler());
writeWorker.execute();
readWorker.execute();
shutDownLatch = new CountDownLatch(2);
shutDownLatch.await();
} catch (IOException ex) {
ex.printStackTrace();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
protected class PropertyChangeHandler implements PropertyChangeListener {
@Override
public void propertyChange(PropertyChangeEvent evt) {
SwingWorker worker = (SwingWorker) evt.getSource();
if (worker.getState() == SwingWorker.StateValue.DONE) {
shutDownLatch.countDown();
// Not interested in the return value, only interested in the
// exception if one was thrown...
try {
worker.get();
} catch (InterruptedException | ExecutionException ex) {
// Resync the error with the UI, probably using SwingUtilities.invokeLater
// and call some error handling method
ex.printStackTrace();
}
}
}
}
}
public class WriteWorker extends SwingWorker {
private OutputStream os;
private List<String> queue = new ArrayList<String>(25);
private ReentrantLock queueLock = new ReentrantLock();
private Condition queueCondition = queueLock.newCondition();
public WriteWorker(OutputStream os) {
this.os = os;
}
public void write(String text) {
queueLock.lock();
try {
queue.add(text);
queueCondition.signal();
} finally {
queueLock.unlock();
}
}
@Override
protected Object doInBackground() throws Exception {
while (!isCancelled()) {
String text = null;
while (text == null && !isCancelled()) {
queueLock.lock();
try {
if (queue.isEmpty()) {
queueCondition.await();
}
if (!queue.isEmpty()) {
text = queue.remove(0);
}
} finally {
queueLock.unlock();
}
if (text != null) {
os.write(text.getBytes());
}
}
}
return null;
}
}
public class ReadWorker extends SwingWorker<Void, String> {
private InputStream is;
private JTextArea ta;
public ReadWorker(InputStream is, JTextArea ta) {
this.is = is;
this.ta = ta;
}
@Override
protected void process(List<String> chunks) {
for (String text : chunks) {
ta.append(text);
}
}
@Override
protected Void doInBackground() throws Exception {
byte[] buffer = new byte[4096];
int bytesRead = -1;
while (!isCancelled() && (bytesRead = is.read(buffer)) != -1) {
String text = new String(buffer, 0, bytesRead);
publish(text);
}
return null;
}
}
关于java - 在java中通过客户端服务器网络将进程输出打印到JTextArea,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60593207/
我有一个简单的 GUI,其中有一个 JTextArea。我创建了一个方法来从用户获取消息,另一个方法将文本附加到文本区域,如下所示 Message m = new Message(); ... pri
我正在使用 JList,并且尝试对单元格使用 JTextAreas(实现 ListCellRenderer)。它不起作用。这些单元格仅显示 ListCellRenderer.toString() 而不
此代码计算 JTextArea 的每一行并添加行数 左 JTextPane import java.awt.BorderLayout; import java.awt.Color; import ja
就目前情况而言,这个问题不太适合我们的问答形式。我们希望答案得到事实、引用资料或专业知识的支持,但这个问题可能会引发辩论、争论、民意调查或扩展讨论。如果您觉得这个问题可以改进并可能重新开放,visit
我必须将一个jtextarea的内容复制到另一个jtextarea。怎么办?我已经做了以下操作:但是这个程序正在将一个jtext区域的文本逐个字符写入另一个jtext区域。我希望它在用户按下回车键时复
在我的 GUI 中,JScrollPane 中有一个附加到容器的 JTextArea。 ta = new JTextArea(); jsp = new JScrollP
我正在编写一些测试代码来练习 OOP,我想将 JTextArea 从“writeToArea”附加到定义和初始化 JTextArea 的“initialize”方法。我已经尝试直接调用“输出”变量,但
JComboBox cBox = new JComboBox(); cBox.addItem("Food"); String x = "Food"; cBox.addItem("Shi
我正在尝试将一个 JTextArea 放在 GUI 中的另一个 JTextArea 旁边 我正在为数据库编写 GUI,并希望将每列的数据放在不同的 JTextArea 中。这将使我的 GUI 看起来更
这是一个带有 JTextarea 的弹出 Jpanel,但我有一个问题。当我将鼠标移到 JTextarea 上时,它会闪烁。为什么会出现这种情况? 在 Debug模式下,鼠标移动会生成 mouseEx
我有一个类将输出显示到 JTextArea 中。意味着成功运行后,它将在文本区域中显示输出。 我还有一个主类,它将类与几个按钮组合在一起,以启动特定类中代码的执行。这个主类创建了一个带有几个按钮的 G
我的问题在于我的 DocumentLister AreaListener。我似乎无法弄清楚如何将用户输入的文本传递到一个 JTextArea 中进行转换,并将其返回到另一个 JTextArea。 该程
我有一个对象ReminderGUI其中有 JTextArea field 。 ReminderGUI代表一个可以保存和显示提醒的应用程序。当getReminderButton单击我希望应用程序找到之前
我目前正在使用 Swing 开发控制台窗口。它基于 JTextArea 并且像普通命令行一样工作。您在一行中键入一条命令,然后按回车键。在下一行中,显示了输出,在该输出下,您可以编写下一条命令。 现在
我开发了一个 Swing GUI,其中我尝试使用按钮使用另一个文本区域中的文本填充文本区域。 代码: private void jButton1ActionPerformed(java.awt.eve
当我制作时,我有一个包含 JPanel 的小型 GUI,其中有 JTextArea 和 JLabel panel1.setLayout(null); 我可以完成所需的位置,但 JTextArea 消失
我在 JDialog 框中有一个 JTabbedPane,它在 Pane 中包含的所有 JPanels 上使用 GridBagLayout 。在显示的第一个面板上有一个 JTextArea (desc
我搜索了答案,但我找到的只是解决方法,而不是原因,所以我问这个问题: 我是 GUI 编程的新手。在练习一些有关关键事件处理的代码时,我遇到了一个示例,该示例在 JFrame 中包含一个 JTextAr
将有 91 个文本区域,每个区域都显示一个值。我试图找到一种更有效的方法来解决这个问题,而不是只是盲目地添加 JTextAreas 并尝试管理 91 个文本区域中每个区域的实例化名称。 我愿意接受有关
private JPanel contentPane; public Driver() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
我是一名优秀的程序员,十分优秀!