有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

单击按钮时jtable 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);
    }

}

共 (1) 个答案

  1. # 1 楼答案

    要清除,只需将模型的行数设置为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")) {
    

    这之所以重要是因为==检查一个字符串对象是否与另一个字符串对象相同,而您实际上并不关心这一点。相反,您想知道一个字符串是否与另一个字符串具有相同的字符,这就是equals测试的目的

    另外,我在计算方法开始时将模型的行数设置为0,这样您就可以重新计算,而无需清除