从不同的类写入jTextArea [英] Write to jTextArea from different class

查看:151
本文介绍了从不同的类写入jTextArea的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想知道是否可以从一个单独的类附加到一个类中的jTextArea?我基本上有一个简单的类,它不断运行计算,我想在我自己的类中创建的GUI上查看输出。程序通过System.out.println执行正常,但我想在我的textarea上查看它。非常感谢任何指导。

Just wondering if it is possible to append to a jTextArea in one class from a separate class? 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. The program executes fine via System.out.println but I want to view this on my textarea now. 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);

我希望将此输出写入单独的jTextArea,该jTextArea位于下面的另一个类中class。

I want this output to be written to a seperate jTextArea which is in another class which is below the below 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类(GUI)

SocketForm Class (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                   

}

推荐答案

建议:


  • 为GUI类提供一个公共方法, public void appendText(String text )只是将文本字符串附加到JTextArea。

  • 任何希望将文本附加到JTextArea的外部类只需要对该类有有效的引用有这个方法,然后需要调用它。

  • 必须注意确保只在Swing事件线程EDT上调用此方法。

  • 由于您将从长时间运行的代码中执行此操作,因此您需要执行Swing事件线程的长时间运行代码 off 。 SwingWorker可以很好地完成这项工作。谷歌并学习本教程,因为它非常有用。

  • 你应该考虑专门使用 SwingWorker< Void,String> 并使用发布/处理方法对将字符串从服务器发送到JTextArea,在Swing E vent D ispatch T hread或EDT上。

  • 从不 在上面的代码中显示一个空的catch块, catch(IOException e) {} 。这是与闭着眼睛驾驶摩托车相当的编码。是的,一开始看起来很有趣,但几乎总是会很糟糕。

  • Give the GUI class a public method, public void appendText(String text) that simply appends the text String to the 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.
  • Care must be taken to be sure to only call this method on the Swing event thread, the 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. A SwingWorker will work well for this. Google and study the tutorial as it will be quite useful.
  • 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 Event Dispatch Thread or EDT.
  • Never have an empty catch block as you show in your code above, 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.

编辑

你state:

Edit
You state:


如果你说它只适合在EDT上运行它怎么能在已经在线程中定义正在运行?

"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?"

我知道两种方式:


  1. 将SwingWorker用作后台线程,并使用发布/进程方法对。检查SwingWorker教程,因为这里有详细描述,或者

  2. 使用标准后台线程并将任何Swing调用放在您传递给 SwingUtilities的Runnable中。 invokeLater(...)方法。

  1. Use a SwingWorker for the background thread, and use the publish/process method pair for this. Check the SwingWorker tutorial as this is well described there, or
  2. Use a standard background thread and put any Swing calls inside of a Runnable that you pass to the SwingUtilities.invokeLater(...) method.

这篇关于从不同的类写入jTextArea的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆