java - 无法从另一个类打印到 JTextArea

标签 java jtextarea

我正在尝试从另一个类打印到我的 JTextArea。我的主类 Risk_Mgnt_Manager 中有类 ActivityLogger 调用方法 Alert,这是 JTextArea 所在的位置。我可以将字符串传递到此方法中并打印给顾问,但它不会将文本附加或设置到 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);
    }
}

最佳答案

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

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

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

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

无论你做什么,都不要试图通过静态化来解决这个问题,因为那条路会导致痛苦。

关于java - 无法从另一个类打印到 JTextArea,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20640557/

相关文章:

java - Mac OS 和 java.awt.Window.init(Window.java :497)) 处的 java.lang.NullPointerException

java - getRequests() 必须返回一个可迭代的数组

java - 是否可以在android上随处设置转换速度/时间

java - 在 Java 的 JTextArea 中区分拖动和选择

java - Java 中可撤消的文本区域

java - 使用一个类中的方法到另一个类中

java - 无法调用自定义标签jsp

java - 使用 JToggleButton 更新 JTextArea

java - 让 JTextArea 显示不带抗锯齿的固定宽度字体

java - 在 JTextArea 上调度关键事件不会移动插入符