单击按钮时java清除表

标签 java jtable jscrollpane

我正在为类编写一个抵押贷款计算器,我让它按照我需要的方式工作,除了每次我单击“计算”按钮时,它只会继续添加到表中,而不是清除表并显示新值。我知道我的代码可能看起来有点草率,并且我注释掉了一些不需要的内容,因为我仍在使用它,但是您有什么建议吗?

仅供引用我还是一个学习 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 - 就是这样:

  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 对象相同,而您实际上并不关心这一点。相反,您想知道一个字符串是否与另一个字符串包含相同的字符,这就是 equals 测试的目的。

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

关于单击按钮时java清除表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6879865/

相关文章:

java - Hibernate Envers 条件审核,运行时忽略自定义 EnversIntegrator

java - JTable 无法添加滚动条

java - 滚动 JScrollPane 时出现问题 - 线程

Java Swing : Maximising a JTable display

java - 如何在 Eclipse 中包含 Java 源代码?

java - Apache POI Java - 写入 Excel 并动态更新单元格

java - 在 JAVA (org.json) 中从字符串创建 JSONObject

java - 如何获得更新后的排序后 TableModel?

java - 使用 AbstractTableModel 在 Jtable 中添加行

java - 如何使用键盘箭头键将行标题 JTable 滚动与另一个表同步