2011-07-29 80 views
1

我正在寫一個按揭計算器的類,我有它的工作方式,我需要它,除了每次我點擊「計算」按鈕它只會繼續添加到表而不是表格清理並顯示新的價值。我知道我的代碼可能看起來有些sl and,而且我有些事情已經評論說不需要在那裏,因爲我仍在工作,但是您有什麼建議嗎?java按鈕點擊清除表

僅供參考我還是一個初學者學習Java和它採取了我過去20小時爲止得到這個(與我「敢爲自己感到驕傲!)謝謝!!

//Import all required Packages 
import javax.swing.*; 
import javax.swing.table.*; 
import java.awt.*; 
import java.text.*; 
import java.awt.event.*; 

public class MortgageCalculator extends JFrame implements ActionListener { 


// Loan Values 
double intPrincipal, interestRate, calcPayment, monthlyInterest, currentInterest, principalPaid, newBalance; 

int totalMonths; 

double[] loanInterest = {5.35, 5.5, 5.75}; // Yearly interest in decimal form 
int[] loanTerm = {7, 15, 30}; // Total months of term 
String principal; 
String comboArray[] = {"7 Years at 5.35%", "15 Years at 5.5%", "30 Years at 5.75%"}; 
int termYears, termMonths, done, i=0, m=0, p=0; 



//Set up panels 
JPanel contentPanel; 

//Set up labels 
JLabel mortgageLabel, paymentLabel, termLabel; 

//Set up buttons 
JButton calculateButton, clearButton, exitButton; 

//TextFields 
JTextField txtMortgage = new JTextField(10); 
JTextField txtPayment = new JTextField(10); 

//New Text Area 
JTextArea textarea = new JTextArea(); 

DecimalFormat df = new DecimalFormat("$###,###.00"); //Formatting the results to decimal form 


//Combo Box 
JComboBox loansList = new JComboBox(); 

DefaultTableModel model = new DefaultTableModel(); 
JTable table = new JTable(model); 

//Build GUI 
    public MortgageCalculator() 
    { 
    super(); 
    initializeContent(); 
    } 

    public void initializeContent() 
       { 
        this.setSize(700, 500); 
        this.setLocation(0, 0); 
        this.setContentPane(contentPanel()); 
        this.setTitle("Mortgage Calculator"); 
       } 

    public JPanel contentPanel() 
       { 

        contentPanel = new JPanel(); 
        contentPanel.setLayout(null); 


        //Add labels to the panel 
        mortgageLabel = new JLabel("Mortgage:"); 
        mortgageLabel.setLocation(200, 30); 
        mortgageLabel.setSize(100, 25); 
        contentPanel.add(mortgageLabel); 

        termLabel = new JLabel("Term & Rate:"); 
        termLabel.setLocation(183, 55); 
        termLabel.setSize(100, 30); 
        contentPanel.add(termLabel); 

        paymentLabel = new JLabel("Monthly Payment:"); 
        paymentLabel.setLocation(158, 85); 
        paymentLabel.setSize(100, 30); 
        contentPanel.add(paymentLabel); 

        //Text Fields 

        txtMortgage = new JTextField(10); 
        txtMortgage.setLocation(280, 30); 
        txtMortgage.setSize(150, 25); 
        contentPanel.add(txtMortgage); 

        txtPayment = new JTextField(10); 
        txtPayment.setLocation(280, 85); 
        txtPayment.setSize(150, 25); 
        contentPanel.add(txtPayment); 


        //Combo Box 

        loansList.addItem(comboArray[0]); 
        loansList.addItem(comboArray[1]); 
        loansList.addItem(comboArray[2]); 
        loansList.setLocation(280, 55); 
        loansList.setSize(150, 25); 
        loansList.addActionListener(this); 
        contentPanel.add(loansList); 


        //textarea.setPreferredSize(new Dimension(650, 300)); 


        //JScrollPane scroller = new JScrollPane(textarea); 
        JScrollPane scroller = new JScrollPane(table); 
        contentPanel.add(scroller); 
        scroller.setSize(650,300); 
        scroller.setLocation(20, 150); 


        textarea.setLineWrap(true); 

        model.addColumn("Payment Number"); 
        model.addColumn("Current Interest"); 
        model.addColumn("Principal Paid"); 
        model.addColumn("New Balance"); 



        //Buttons 
        exitButton = new JButton("Exit"); 
        exitButton.setLocation(450, 30); 
        exitButton.setSize(100, 25); 
        contentPanel.add(exitButton); 

        clearButton = new JButton("Clear"); 
        clearButton.setLocation(450, 55); 
        clearButton.setSize(100, 25); 
        contentPanel.add(clearButton); 


        calculateButton = new JButton("Calculate"); 
        calculateButton.setLocation(450, 85); 
        calculateButton.setSize(100, 25); 
        contentPanel.add(calculateButton); 

        //setup up buttons 
        calculateButton.addActionListener(this); 
        clearButton.addActionListener(this); 
        exitButton.addActionListener(this); 


        return contentPanel; 

       } 




    //Define actions performed for buttons 
    public void actionPerformed(ActionEvent e) 
    { 

      String arg = e.getActionCommand(); 
      if (e.getSource() == loansList) { 
       switch (loansList.getSelectedIndex()) { 
         case 0: 
           i = 0; 
           break; 
         case 1: 
           i = 1; 
           break; 
         case 2: 
           i = 2; 
           break; 
       } 
      } 

      if (arg == "Calculate") 
      { 

       txtPayment.setText(""); 
       principal = txtMortgage.getText(); 
       try { 
          intPrincipal = Double.parseDouble(principal); 
          if (intPrincipal <= 0) throw new NumberFormatException(); 
        } 
        catch(NumberFormatException n){ 
          txtPayment.setText("Please Enter a Postive Numeric Number"); 
          done = 1; 
        } 
       if (done == 1) 
         done = 0; 
       else { 

          interestRate = loanInterest[i]; 
          termYears = loanTerm[i]; 
          monthlyInterest = interestRate/(12*100); //calculates monthly interest 
          termMonths = termYears*12; //calculates term length in months 
          calcPayment = monthlyInterest*intPrincipal/(1-Math.pow((1+monthlyInterest), -termMonths)); //calculates monthly payment 
          txtPayment.setText(" " + df.format(calcPayment)); 

          for (m=0; m<=totalMonths; m++) { 
           totalMonths = loanTerm[i]*12; 
           currentInterest = intPrincipal * monthlyInterest; 
           principalPaid = calcPayment - currentInterest; 
           newBalance = intPrincipal - principalPaid; 
           intPrincipal = newBalance; 

           /* printAndAppend(
           (m+1) + "   " + 
           df.format(currentInterest) + "      " + 
           df.format(principalPaid) + "   " + 
           df.format(newBalance) + "\n"); 
           //textarea.setText(df.format(currentInterest)); 

           if(intPrincipal <= 1){ break;}*/ 


           // Create a couple of columns 


           model.addRow(new Object[]{m+1, df.format(currentInterest), df.format(principalPaid), df.format(newBalance)}); 

           if(intPrincipal <= 1){ break;} 



          } 


      } 
    } 

      else if (e.getSource() == clearButton) 
      { 
       txtMortgage.setText(""); //clear Mortgage textfield 
       txtPayment.setText(""); //clear Payment textfield 
       txtMortgage.requestFocusInWindow(); //move cursor back to Mortgage textfield 
       loansList.setSelectedIndex(0); 
      } 

      else if (e.getSource() == exitButton) 
       System.exit(0); 
     } 

    public void printAndAppend(String text) { 
     textarea.append(text); 
    } 

    public static void main(String[] args) 
    { 
     new MortgageCalculator().setVisible(true); 
    } 

} 
+0

嘗試'model = new DefaultTableModel();'每當你想清除表 –

+0

我有我的代碼頂部「DefaultTableModel模型=新DefaultTableModel();」我需要把它放在別的地方嗎? – Dawn

+0

在'for(m = 0; m <= totalMonths; m ++)之前加上它' –

回答

2

要清除所有你需要做的是設置模型的行數爲0 - 這是它:

else if (e.getSource() == clearButton) { 
    txtMortgage.setText(""); 
    txtPayment.setText(""); 
    txtMortgage.requestFocusInWindow(); 
    loansList.setSelectedIndex(0); 

    model.setRowCount(0); //!! added 
    } 

此外,這是不好:

if (arg == "Calculate") { 

因爲你不應該使用==來比較字符串。如果要比較字符串,使用equals方法:

if (arg.equals("Calculate")) { 

或equalsIgnoreCase方法:

if (arg.equalsIgnoreCase("Calculate")) { 

的原因,這是很重要的是因爲==檢查是否一個String對象是一樣的作爲另一個String對象,你真的不關心這個。相反,你想知道一個字符串是否與另一個字符串持有相同的字符,這就是等於測試的字符串。

此外,我會在您的計算方法開始時將模型的行數設置爲0,這樣您就可以重新計算事物而無需清除。

+0

謝謝!這是完美:) – Dawn

+1

@Dawn:不客氣!接下來我們將使用佈局管理器。 :) –

+0

哇,Java是一個怪物!雖然我花了一段時間才弄清楚如何編寫這個程序,但我很開心。 – Dawn