简体   繁体   English

无法从另一个类打印到JTextArea

[英]Can't print to JTextArea from another class

I am attempting to print to my JTextArea from another class. 我试图从另一个类打印到我的JTextArea。 I have the class ActivityLogger call method Alert inside of my main class Risk_Mgnt_Manager which is where the JTextArea is located. 我的主类Risk_Mgnt_Manager中有JLogArea所在的类ActivityLogger调用方法Alert。 I am able to pass the string into this method and print to counsel but it won't append or setText to the JTextArea. 我能够将字符串传递给此方法并打印给顾问,但不会将其附加或设置到JTextArea。 What am I missing? 我想念什么?

My goal is to have different classes send messages to the class ActivityLogger which in turn sends it to the JTextArea. 我的目标是让不同的类将消息发送到ActivityLogger类,后者再将其发送到JTextArea。

Any examples are appreciated and Thank you in advance. 任何示例表示赞赏,并提前谢谢。

Main class 主班

package risk_mgnt_manager;

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;

public class Risk_Mgnt_Manager extends JFrame{
    boolean begin = false;
    String message = null;
    JTextArea text = new JTextArea();
    JButton Start = new JButton("Start");//exit program button
    JButton End = new JButton("End");//Ok button executes message creation
    JButton Exit = new JButton("Exit Program");

public void Alert(String a){
    System.out.println(a); // This is printing correctly  
    text.append(a + "\n"); // why won't this display the string?
}

public Risk_Mgnt_Manager(){
    text.setEditable(false);
    text.setWrapStyleWord(true);
    text.setLineWrap(true);
    JScrollPane scroll = new JScrollPane(text);

    setLayout(new GridLayout(2, 3, 5, 5)); //LayoutManager Setup
    JPanel myPanel = new JPanel(new GridLayout(3,0));
    //JPanel myPanel2 = new JPanel(new GridLayout(1, 1));
    //JPanel myPanel3 = new JPanel(new GridLayout(1, 1));
    JPanel myPanel4 = new JPanel(new GridLayout(1, 1));

    myPanel.add(new JLabel("Start Automated Processes: "));
    myPanel.add(Start);

    myPanel.add(new JLabel("End Automated Processes: "));
    myPanel.add(End);

    myPanel.add(new JLabel("  "));
    myPanel.add(Exit);
    myPanel4.add(text);

    Start.addActionListener(new startActions());//Listener for button 1
    End.addActionListener(new stopActions());//Listener for button 2
    Exit.addActionListener(new Quit());//Listener for button 2

    add(myPanel);
    //add(myPanel2);
    //add(myPanel3);
    add(myPanel4);

}

public void StartAutomation(boolean start) throws SAXException,     ParserConfigurationException, IOException, SQLException{
        //calls test class
        Test t = new Test();
        t.mainTest(begin);

        //ignore these classes
        // Step one import settlement data from FIX 1 settlement tables
        ImportSettles tbl = new ImportSettles();
        //tbl.DataTransfer(begin);

        // Step two import Real-Time price data from t_span_price on FIX 1
        ImportSpanPrice tbl2 = new ImportSpanPrice();
        //tbl2.DataTransfer1(begin);

        // Step three import from xml file
        ImportTradeData tbl3 = new ImportTradeData();
        //tbl3.parseXML(begin);

        // Step four not used as of 11/26/2013
        ImportFirmRpt tbl4 = new ImportFirmRpt();

        // Step five import poew.csv file
        ImportPOEW tbl5 = new ImportPOEW();
        //tbl5.csvImportPOEW(begin);

        // Step six import paycollect.csv file
        ImportPaycollect tbl6 = new ImportPaycollect();
        //tbl6.csvImportPaycollect(begin);

        // Step seven import data from RISK 1
        ImportSecDeposit tbl7 = new ImportSecDeposit();
        //tbl7.DataTransfer2(begin);

        // Step 8 import FCM financial info, WinJammer not used as of 11/26/2013
        ImportFCM tbl8 = new ImportFCM();


        // Step nine import CGM_post.csv file
        ImportCGMPost tbl9 = new ImportCGMPost();
        //tbl9.csvImportCGMPost(begin);

        // Step ten import RM_Intraday_paycollect.csv
        ImportIntraday tbl10 = new ImportIntraday();
        //tbl10.csvImportIntra(begin);   
}

private static void ProjectFrame(){
    Risk_Mgnt_Manager projectFrame = new Risk_Mgnt_Manager();
    projectFrame.setSize(500, 300); //JFrame size set
    projectFrame.setLocationRelativeTo(null); //JFrame centered to center of screen
    projectFrame.setTitle("Automation Control"); //JFrame Title
    projectFrame.setVisible(true);//JFrame is visible upon start of program
    projectFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}



public static void main(String[] args) {
    ProjectFrame();
}
static class Quit implements ActionListener {
        public void actionPerformed (ActionEvent e) {
            //Once Exit JButton is pressed the program exits
            System.exit(0);
        }
    }
public class startActions implements ActionListener {
        public void actionPerformed (ActionEvent e) {
            //Once Exit JButton is pressed the program exits
            begin = true;
            try {
                StartAutomation(begin);
            } catch (SAXException ex) {
                Logger.getLogger(Risk_Mgnt_Manager.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ParserConfigurationException ex) {
                Logger.getLogger(Risk_Mgnt_Manager.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(Risk_Mgnt_Manager.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SQLException ex) {
                Logger.getLogger(Risk_Mgnt_Manager.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
public class stopActions implements ActionListener {
        public void actionPerformed (ActionEvent e) {
            //Once Exit JButton is pressed the program exits
            begin = false;
            try {
                StartAutomation(begin);
            } catch (SAXException ex) {
                Logger.getLogger(Risk_Mgnt_Manager.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ParserConfigurationException ex) {
                Logger.getLogger(Risk_Mgnt_Manager.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(Risk_Mgnt_Manager.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SQLException ex) {
                Logger.getLogger(Risk_Mgnt_Manager.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    } 
} 

Test class 测试班

package risk_mgnt_manager;

import java.util.Date;

/**
 *
 * @author bgilbert
 */
public class Test {
    public void mainTest(boolean a){
        ActivityLogger act = new ActivityLogger();
        act.logger("Testing message reporting " + new Date(), 1, true);
}

}

ActivityLogger class ActivityLogger类

package risk_mgnt_manager;
/**
 *
 * @author MLaMeyer
 */
public class ActivityLogger{
     private String message;

    // this will perform different purposes once I can print to JTextArea
    public void logger(String log, int type, boolean execution){
    if (execution == true) {

                message = log;
    } 
            if (execution == false) {

                message = log;
    } 

            print();

}
    // calls method Alert in main class and passes the string correctly
    public void print(){
      Risk_Mgnt_Manager m = new Risk_Mgnt_Manager();
      m.Alert(message);
    }
}

You need to update the UI in separate Thread , I mean UI related operations should run on the Event dispatch thread. 您需要在单独的Thread更新UI,这意味着与UI相关的操作应在Event派发线程上运行。 Add constructor in your ActivityLogger class like Hovercraft's solution then try, 像Hovercraft的解决方案一样,在ActivityLogger类中添加构造函数,然后尝试,

SwingUtilities.invokeLater(new Runnable() {
    public void run() {
      text.append(a+"\n");
    }
 });

Your program prints out to the other class, just not in the object displayed: 您的程序将输出到另一个类,但不会显示在所显示的对象中:

public void print(){
  Risk_Mgnt_Manager m = new Risk_Mgnt_Manager();
  m.Alert(message);
}

When you create a new Risk_Mgnt_Manager, you do just that, create a new completely unique Risk_Mgnt_Manager object, one that is not displayed. 创建新的Risk_Mgnt_Manager时,只需执行此操作,即创建一个新的完全唯一的Risk_Mgnt_Manager对象,该对象不会显示。 Printing to it will have no effect on the displayed one. 打印到它不会对显示的内容产生任何影响。

A the solution is to pass in a reference to your logger class to the actual displayed Risk_Mgnt_Manager object. 一种解决方案是将对记录器类的引用传递给实际显示的Risk_Mgnt_Manager对象。

public class ActivityLogger{
     private String message;
     private Risk_Mgnt_Manager m; // ***** added

     public ActivityLogger(Risk_Mgnt_Manager m) {
       this.m = m; // ****** added
     }

    // this will perform different purposes once I can print to JTextArea
    public void logger(String log, int type, boolean execution){
    if (execution == true) {

                message = log;
    } 
            if (execution == false) {

                message = log;
    } 

            print();

}
    // calls method Alert in main class and passes the string correctly
    public void print(){
      // Risk_Mgnt_Manager m = new Risk_Mgnt_Manager();
      SwingUtilities.invokeLater(new Runnable() {
        public void run() {
          m.Alert(message);
        }
      });
    }
}

Whatever you do, don't attempt to solve this my making anything static as that road will lead to misery. 无论您做什么,都不要尝试解决此问题,因为这条道路会导致痛苦,因此我无法将任何事情变为静态。

First of all make the frame visible in your constructor . 首先,使框架在constructor可见。

public Risk_Mgnt_Manager(){

setVisible(true);

}

Then as per solution by Hovercraft pass by reference. 然后根据气垫船的解决方案通过参考。

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

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