Java Can';t从另一个类打印到JTextArea

Java Can';t从另一个类打印到JTextArea,java,jtextarea,Java,Jtextarea,我正试图从另一个类打印到我的JTextArea。我的主要类风险管理器中有类活动记录器调用方法警报,JTextArea位于该类风险管理器中。我可以将字符串传递到这个方法中并打印到Advisor,但它不会向JTextArea追加或设置文本。我错过了什么 我的目标是让不同的类向类ActivityLogger发送消息,后者反过来将消息发送到JTextArea 任何例子都将不胜感激,并提前向您表示感谢 主类 package risk_mgnt_manager; import java.awt.GridL

我正试图从另一个类打印到我的JTextArea。我的主要类风险管理器中有类活动记录器调用方法警报,JTextArea位于该类风险管理器中。我可以将字符串传递到这个方法中并打印到Advisor,但它不会向JTextArea追加或设置文本。我错过了什么

我的目标是让不同的类向类ActivityLogger发送消息,后者反过来将消息发送到JTextArea

任何例子都将不胜感激,并提前向您表示感谢

主类

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);
            }
        }
    } 
} 
测试班

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);
}

}
活动记录器类

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);
    }
}

您需要在单独的
线程中更新UI,我的意思是UI相关的操作应该在事件分派线程上运行。在ActivityLogger类中添加构造函数,如气垫船的解决方案,然后重试

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

您的程序打印到另一个类,而不是显示在对象中:

public void print(){
  Risk_Mgnt_Manager m = new Risk_Mgnt_Manager();
  m.Alert(message);
}
创建新的风险管理器时,只需创建一个新的完全唯一的风险管理器对象,该对象不显示。打印到它将不会对显示的内容产生影响

解决方案是将对记录器类的引用传递给实际显示的风险管理器对象

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);
        }
      });
    }
}

无论你做什么,都不要试图解决这个问题,因为我让任何东西都静止不动,因为那条路会导致痛苦

首先,使框架在
构造函数中可见

public Risk_Mgnt_Manager(){

setVisible(true);

}

然后根据气垫船的解决方案通过引用传递。

@hovercraftfullofels很好的建议,但不一定要添加。既然ActivityLogger需要参数,我是否也必须通过引用将对象传递给我的测试类?@user1789170:对不起,我不确定我是否理解您的问题。@user1789170:底线是您不能只登录到任何ole风险管理器对象,而是必须在引用当前显示的风险管理器对象时调用
alert(…)
。由您决定如何连接引用,但必须以某种方式完成。既然您在ActivityLogger中创建了默认构造函数,测试类需要将参数值传递给默认构造函数。这是否正确,或者我的测试类是否有其他方法在ActivityLogger类中调用logger方法。我不知道如何做到这一点。谢谢你迄今为止的帮助。这是有道理的,我正在学习很多,所以我只需要找到一种方法来通过它。非常感谢。