简体   繁体   English

从不同的类写入jTextArea

[英]Write to jTextArea from different class

Just wondering if it is possible to append to a jTextArea in one class from a separate class? 只是想知道是否可以将一个类中的jTextArea追加到一个单独的类中? I basically have a simple class that is constantly running calculations and I want to view the output on a GUI which I have created in its own class. 我基本上有一个不断运行计算的简单类,我想在自己的类中创建的GUI上查看输出。 The program executes fine via System.out.println but I want to view this on my textarea now. 该程序可以通过System.out.println执行良好,但我现在想在我的textarea上查看。 Many thanks in advance for any guidance. 在此先感谢您的指导。

Updated - The code below is what I am running. 已更新-以下代码是我正在运行的代码。 The area in question is the following (This is a method from a rather large class) : 有问题的区域如下(这是一个很大类的方法):

System.out.println("From Server:" + sentenceFromServer);

I want this output to be written to a seperate jTextArea which is in another class which is below the below class. 我希望将此输出写入单独的jTextArea,它位于下面的类之下的另一个类中。

Client Class 客户类别

public void run() {
   SocketForm form = new SocketForm();
    //File file=null;

  long startTime; // Starting time of program, in milliseconds.
  long endTime;   // Time when computations are done, in milliseconds.
  double time; 
  System.out.println("Variables Set");
  String serverName = "localhost";
   try {
    //if (args.length >= 1)
       // serverName = args[0];
  InetAddress serverIPAddress = InetAddress.getByName(serverName);

    //get server port;
    int serverPort = form.cliportNo;
    //if (args.length >= 2)
      //  serverPort = Integer.parseInt(args[1]);
    //create socket
    DatagramSocket clientSocket = new DatagramSocket();
    //get input from keybaord
    byte[] sendData = new byte[byteSize];
    //BufferedReader inFromUser = new BufferedReader(new InputStreamReader (System.in));
    //while (true){
    //String sentence = inFromUser.readLine();
    startTime = System.currentTimeMillis();
    //sendData = sentence.getBytes();
    System.out.println("About to identify image");
    String fileName = "/Users/Andrew/Desktop/pic.jpg";
    File f = new File(fileName);

    FileInputStream fis = null;
    try {
        fis = new FileInputStream(f);
        System.out.println("Total file size to read in bytes is : " + fis.available());

    } catch (IOException e) {}


 Path path = Paths.get("/Users/Andrew/Desktop/pic.jpg");
 //byte[] data = Fles.readAllBytes(path);
  sendData = Files.readAllBytes(path);   

    try {
    for( int index = 0; index < sendData.length ; index += byteSize ) {
     DatagramPacket packet = new DatagramPacket( sendData, index, Math.min( byteSize, sendData.length-index ), serverIPAddress, serverPort);
     clientSocket.send(packet);
    //DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, serverIPAddress, serverPort);

    //receive datagram
    byte[] receiveData = new byte [byteSize];

    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
    clientSocket.receive(receivePacket);
    //print output
    String sentenceFromServer = new String(receivePacket.getData());
    System.out.println("From Server:" + sentenceFromServer);
    }
    System.out.println("The End");
    }
    catch (Exception e) {}
    //close client socket
            //clientSocket.close();
        endTime = System.currentTimeMillis();
  time = endTime - startTime;
      System.out.println("Time :" + time);
   // }
}
   catch (Exception e) {}
}

SocketForm Class (GUI) SocketForm类(GUI)

public static void main(String args[]) {
    /* Set the Nimbus look and feel */
    //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
    /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
     * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
     */
    try {
        for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
            if ("Nimbus".equals(info.getName())) {
                javax.swing.UIManager.setLookAndFeel(info.getClassName());
                break;
            }
        }
    } catch (ClassNotFoundException ex) {
        java.util.logging.Logger.getLogger(SocketForm.class.getName()).log(java.util.logging.Level.SEV
    }
    //</editor-fold>

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new SocketForm().setVisible(true);
        }
    });
}
// Variables declaration - do not modify                     
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTabbedPane jTabbedPane1;
public static javax.swing.JTextArea jTextArea1;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;

// End of variables declaration                   

} }

Suggestions: 意见建议:

  • Give the GUI class a public method, public void appendText(String text) that simply appends the text String to the JTextArea. 给GUI类一个公共方法, public void appendText(String text) ,该方法将文本String附加到JTextArea。
  • Any outside class that wishes to append text to the JTextArea only needs to have a valid reference to the class that has this method, and then needs to call it. 希望将文本追加到JTextArea的任何外部类仅需要对具有此方法的类进行有效引用,然后调用它。
  • Care must be taken to be sure to only call this method on the Swing event thread, the EDT. 必须注意确保仅在Swing事件线程EDT上调用此方法。
  • Since you'll be doing this from a long-running bit of code, you'll want to do this long running code off of the Swing event thread. 因为你会从一个代码长期运行位这样做,你会想这样做长时间运行的代码 Swing事件线程。 A SwingWorker will work well for this. SwingWorker将为此很好地工作。 Google and study the tutorial as it will be quite useful. Google并学习该教程,因为它将非常有用。
  • You should consider specifically using a SwingWorker<Void, String> and use the publish/process method pair to send the String from the server to the JTextArea, on the Swing E vent D ispatch T hread or EDT. 你应该考虑具体使用SwingWorker<Void, String>并使用发布/处理方法对从服务器到JTextArea中发送字符串,在摆动Ë通气d ispatchŤhread或EDT。
  • Never have an empty catch block as you show in your code above, catch (IOException e) {} . 如上面代码所示, 永远不要有空的catch块catch (IOException e) {} This is the coding equivalent of driving a motorcycle with your eyes closed. 这相当于闭着眼睛驾驶摩托车。 Yes, it might seem like fun at first, but it will almost always ends badly. 是的,乍一看似乎很有趣,但是几乎总会以糟糕的结果结束。

Edit 编辑
You state: 您声明:

"If it is as you say only suitable to run it on the EDT how can this be defined inside the thread which is already running?" “如果如您所说仅适合在EDT上运行它,那么如何在已经运行的线程中定义它呢?”

I know 2 ways: 我知道两种方式:

  1. Use a SwingWorker for the background thread, and use the publish/process method pair for this. 将SwingWorker用于后台线程,并为此使用publish / process方法对。 Check the SwingWorker tutorial as this is well described there, or 检查SwingWorker教程,因为那里对此有很好的描述,或者
  2. Use a standard background thread and put any Swing calls inside of a Runnable that you pass to the SwingUtilities.invokeLater(...) method. 使用标准的后台线程,并将所有Swing调用放入传递给SwingUtilities.invokeLater(...)方法的Runnable内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM