无法从其他类打印到JTextArea

时间:2013-12-17 17:15:13

标签: java jtextarea

我正在尝试从另一个类打印到我的JTextArea。我在我的主类Risk_Mgnt_Manager里面有类ActivityLogger调用方法Alert,这是JTextArea所在的位置。我能够将字符串传递给此方法并打印到建议,但它不会附加或setText到JTextArea。我错过了什么?

我的目标是让不同的类向ActivityLogger类发送消息,然后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);
}

}

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

3 个答案:

答案 0 :(得分:1)

您需要在单独的Thread中更新UI,我的意思是UI相关的操作应该在Event调度线程上运行。在您的ActivityLogger类中添加构造函数,如Hovercraft的解决方案,然后尝试,

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

答案 1 :(得分:1)

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

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

当您创建新的Risk_Mgnt_Manager时,您只需创建一个新的完全唯一的Risk_Mgnt_Manager对象,即未显示的对象。打印到它将不会影响显示的。

解决方案是将对logger类的引用传递给实际显示的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);
        }
      });
    }
}

无论你做什么,都不要试图解决这个问题,因为这条道路会导致痛苦。

答案 2 :(得分:0)

首先,在constructor

中显示框架
public Risk_Mgnt_Manager(){

setVisible(true);

}

然后按照Hovercraft的解决方案通过引用传递。