简体   繁体   English

将文本从另一个类传递到主类中的jtextArea

[英]Pass text from another class to a jtextArea in the main class

I have a small but elusive problem. 我有一个小但难以捉摸的问题。 I have 2 classes, my package and main class is: 我有2个班级,我的包裹和主要班级是:

    package bankaccount;
    public class BankFrame extends javax.swing.JFrame {

My other class: 我的另一堂课:

public class Account {

    I want to print out a string from Account class to a jTextarea in the
            main class.

I am posting the code from the two classes here as requested. 我根据要求在这里发布了两个类的代码。 first the main class: 第一类:

package bankaccount;
import java.util.Random;

    public class BankFrame extends javax.swing.JFrame {
        public static BankFrame mainContainer;

        int dAmount = 0; // Int for Deposit
        int wAmount = 0; // Int Withdrawal
        String firstName; 
        String surName;
        String name;
        String phone;
        String email;
        String id;
        int numberSize;
        String b;
        String correctId;
        String accountN;
        double balance;
        String newid;
        String passw;     // Password
        String password;  
        String userId;
        String userPassword;
        String savedId;

        /**
         * Creates new form BankFrame
         */
        public BankFrame() {
            initComponents();
        }

        /**
         * This method is called from within the constructor to initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is always
         * regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {
 // I have deleted a lot of init components here.

        private void registerBtnActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:

            Login newUser = new Login(savedId,password);

            password = (regPasswordIn.getText());
            // newUser.setThePassword(password);  //Sparar lösenordet i klassen Login.

            //newUser.setTheId(savedId);        //Sparar personnumret i samma klass.


            if (password.equals("")){
                outReg.setText("Enter a password as required.");

            }else{
                CorrectId();      //Here follows methods to validate a swedish ID-number
            }
        }

        public void CorrectId() {
            id = (regIdIn.getText()); //Ta in id
            id = id.replaceAll("-","").trim();
            if (id.equals("")){
                outReg.setText("Enter your id as required.");
            }else{
                if (validateNumbers(id)){

                    RegPanel.setVisible(false);    //Cardlayout
                    LoginPanel.setVisible(true);
                    base.removeAll();
                    base.add(LoginPanel);
                    revalidate();
                    repaint();

                    savedId=id;

                }else{
                    outReg.setText("Enter a valid ID-number before proceeding");  //Varningstext som även kommer upp 

                }
            }
        }

        public boolean validateNumbers(String nm) {  
            System.out.println("Hej"+nm.length());//debugg
            boolean returnvar;


            numberSize = nm.length();
            if (numberSize != 10) {  
                outReg.setText("Only 10 numbers is allowed!");
                returnvar= false;
            } else {
                returnvar= true;
            }
            return returnvar;
        }

        private void infoBtnActionPerformed(java.awt.event.ActionEvent evt) {
            //Randomgenerators to create a accountnumber. Deleted for this post.
            }

            Account Customer = new Account(accountN, balance, name,email, phone);           
           //Deleted variables for customer information

            //  System.out.println(timsAccount.getNumber() + " name " + timsAccount.getCustomerName());

        }

        private void sBtnActionPerformed(java.awt.event.ActionEvent evt) {

        }

        private void tBtnActionPerformed(java.awt.event.ActionEvent evt) {

            Account Customer = new Account();
            wAmount = Integer.parseInt(withdrawalIn.getText());

 //Amount to withdraw
            dAmount = Integer.parseInt(depositIn.getText()); 
  //Amount to deposit

            Customer.deposit(dAmount);

            Customer.withdrawal(wAmount);
        }

        public void print2transaction (String in){
            System.out.println(in);
            outIn.setText(in);

        }

        private void bBtnActionPerformed(java.awt.event.ActionEvent evt) {

        }
        public void print2balance (String in) {

            Account Customer = new Account(accountN, balance, name,email,   phone);

            double f = Customer.getBalance();

            if (f==0){     //This code is not working. You can ignore this
                outIn.setText("Dishonored customer! Your balance is now $0. If the required amount of $50,000 is not deposited on your account within one week, it will bli terminated according to our rules. Shoo!");
            }else{

                balanceOut.setText("Balance is " + Customer.getBalance());


                //balanceOut.setText

            }
        }

        private void loginBtnActionPerformed(java.awt.event.ActionEvent evt) {

        /**
         * @param args the command line arguments
         */
        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(BankFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(BankFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(BankFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(BankFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
            BankFrame bankFrame = new BankFrame();
            bankFrame.mainContainer=bankFrame;

    /* Create and display the form */
            java.awt.EventQueue.invokeLater(() -> {
                new BankFrame().setVisible(true);

            });
        }

And now the Account class: 现在是Account类:

package bankaccount;

 import java.util.ArrayList;

 public class Account {

private String accountN;
private double balance;
private String b;
private String name;
private String email;
private String phone;
private String d;
private String w;

    public Account() {


}

public Account(String accountN, double balance, String name, String email, String phone) {
    this.accountN = accountN;
    this.balance = balance;        
    this.name = name;
    this.email = email;
    this.phone = phone;

} }

public String getAccountN() {
    return accountN;
}

public void setAccountN(String accountN) {
    this.accountN = accountN;
}

public double getBalance() {
    return balance;
}

public void setBalance(double balance) {
    this.balance = balance;
}


public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getPhone() {
    return phone;
}

public void setPhone(String phone) {
    this.phone = phone;
}

public class AccountArray {

    private String[] theAccount = {accountN, b, name, email, phone};
}

public void deposit(int depositAmount) {
    this.balance += depositAmount;
    BankFrame.mainContainer.print2transaction(" Dearest customer! Depostit of $" + depositAmount + " is acknowledged. New balance is $" + this.balance + ". We are happy to have you, beloved member of the Capitalist family!");
    String b = "" + balance;
    String d = "" + depositAmount;
}

public void withdrawal(int withdrawalAmount) {

    if ((this.balance - withdrawalAmount) == 0 && this.balance != 0) {
        BankFrame.mainContainer.print2transaction("Withdrawal acknowledged. Dishonored customer! Your balance is now $0. If the required amount of $50,000 is not deposited on your account within one week, it will bli terminated according to our rules. Shoo!");
        String b = "" + balance;
        String w = "" + withdrawalAmount;
        /*
         if((this.balance-withdrawalAmount) == 0){         //Kämpat med denna kod men fick inte till det
             if(this.balance ==0){
        toTheTransaction.print2transaction("Withdrawal denied. Dishonored customer! Your balance is $0. If the required amount of $50,000 is not deposited on your account within one week, it will bli terminated according to our rules. Shoo! ");
         */

    } else if (this.balance - withdrawalAmount < 0.0D) {
        BankFrame.mainContainer.print2transaction("Dear customer. Since only $" + this.balance + " is available on your account, your withdrawal was not granted. Goodbye!");
        String b = "" + balance;
        String w = "" + withdrawalAmount;

    } else {
        this.balance -= withdrawalAmount;
        BankFrame.mainContainer.print2transaction("Dearest customer. The withdrawal of $" + withdrawalAmount + " was granted. Remainig balance is: " + this.balance + "$ . We at the Capitalist Bank wishes you a pleasent day!");
        String b = "" + balance;
        String w = "" + withdrawalAmount;

    }

The End... 结束...

Problem Watch my commented line: 问题观看我的评论行:

public class AccountArray {
    private String[] theAccount = {accountN, b, name, email, phone};
}

BankFrame toTheTransaction = new BankFrame(); // This is the problem line, this instance of BankFrame is different than the one that is showing the window

public void deposit(double depositAmount) {
    this.balance += depositAmount;
    if(this.balance !=0.0D){
        toTheTransaction.print2transaction(" Dearest customer...");

Solution: BankFrame.java: 解决方案: BankFrame.java:

package bankaccount;
public class BankFrame extends javax.swing.JFrame {
public static BankFrame mainContainer;
...

public void print2transaction (String in){
    System.out.println(in);
     outIn.setText(in);
        } 


..

public static void main(String[] args)
{
BankFrame bankFrame=new BankFrame();
bankFrame.mainContainer=bankFrame;
...
...
...

}

Class: AccountArray 类:AccountArray

   public class AccountArray {
        private String[] theAccount = {accountN, b, name, email, phone};
    }

public void deposit(double depositAmount) {
    this.balance += depositAmount;
    if(this.balance !=0.0D){
        BankFrame.mainContainer.print2transaction(" Dearest customer...");

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

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