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

时间:2016-10-08 09:59:08

标签: java jtextarea

我有一个小但难以捉摸的问题。我有2个课程,我的课程和主要课程是:

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

我的另一堂课:

public class Account {

    I want to print out a string from Account class to a jTextarea in 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);

            });
        }

现在是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;

    }

结束......

1 个答案:

答案 0 :(得分:0)

<强>问题 观看我的注释行:

.div-table div.appuntamento {
    background-color: #f3f2de;
    padding: 3px 5px;
    border: 1px solid #d7dde6;
    border-radius: 5px;
}
.div-table {
    display:table;         
    width:auto;         
}
.div-table-row{
    display:table-row;
    width:auto;
    clear:both;
    height: 45px;
}
.div-table-col {
    float:left;/*fix for  buggy browsers*/
    display:table-column;         
    width:154px;
}
.div-table-row .div-table-col{
    border-left: 1px solid #d7dde6;
    border-right: 1px solid #d7dde6;
    border-top: 1px solid #d7dde6;
    min-height: 44px;         
}
.div-table-first-col {
    float:left;/*fix for  buggy browsers*/
    display:table-column; 
    text-align: right;
    width: 45px;
}
.div-table-first-col div{
    padding: 3px 5px;
}

解决方案: 的 BankFrame.java:

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...");

类:AccountArray

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;
...
...
...

}