java Очистить таблицу при нажатии кнопки - PullRequest
1 голос
/ 30 июля 2011

Я пишу Ипотечный калькулятор для класса, и у меня он работает так, как мне нужно, за исключением того, что каждый раз, когда я нажимаю кнопку «Рассчитать», он просто будет продолжать добавляться в таблицу вместо очистки таблицы и отображения новых значений.,Я знаю, что мой код может выглядеть немного небрежно, и у меня есть некоторые замечания, которые не должны быть там, потому что я все еще работаю, но есть ли у вас какие-либо предложения?

К вашему сведению Я все еще начинаю изучать 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);
    }

}

1 Ответ

2 голосов
/ 30 июля 2011

Чтобы очистить все, что вам нужно сделать, это установить счетчик строк модели на 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, и вы действительно не заботитесь об этом.Вместо этого вы хотите знать, содержит ли одна строка те же символы, что и другая, и это то, для чего равны тесты.

Кроме того, я бы установил счетчик строк модели равным 0 в начале вашего метода вычисления, и этокак вы можете пересчитать вещи без необходимости очищать.

...