JButton点击事件获取另一个JPanel中JTextField文本

题目:
编写一个计算贷款支付的计算器。这个计算器t让用户输入利率、年数和贷款总额。当点击按钮时,会显示月支付额和总支付额。

界面效果如图:

JButton点击事件获取另一个JPanel中JTextField文本_第1张图片

界面排版:
gridlayout中再放一个gridlayout的JPanel

JButton鼠标点击事件中需要获取JPanel中JTextField的文本用于计算,为了达到目的,定义的的JTextField需要用final修饰

Java中int、double类型转换为String类型:

int -> String
int i=12345;
String s=”“;
第一种方法:s=i+”“;
第二种方法:s=String.valueOf(i);
String -> int
s=”12345”;
int i;
第一种方法:i=Integer.parseInt(s);
第二种方法:i=Integer.valueOf(s).intValue();

代码:

package com.suzi.shangji_04;

import javax.swing.*;

import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class LoanCalculator extends JFrame
{
    public LoanCalculator()
    {
        JPanel p1 = new JPanel();
        p1.setLayout(new GridLayout(5, 2));
        final JTextField t1 = new JTextField(8);
        final JTextField t2 = new JTextField(8);
        final JTextField t3 = new JTextField(8);
        final JTextField t4 = new JTextField(8);
        final JTextField t5 = new JTextField(8);
        p1.add(new JLabel("Annual Interest Rate"));
        p1.add(t1);
        p1.add(new JLabel("Number of years"));
        p1.add(t2);
        p1.add(new JLabel("Loan Amount"));
        p1.add(t3);
        p1.add(new JLabel("Mouthly Payment"));
        p1.add(t4);
        p1.add(new JLabel("Total Payment"));
        p1.add(t5);
        setLayout(new GridLayout(2, 1, 5, 5));

        JButton b1 = new JButton("Compute Payment");
        b1.addMouseListener(new MouseAdapter()
        {
            public void mouseClicked(MouseEvent e)
            {
                try
                {
                    double i = Double.parseDouble(t3.getText())
                            + (0.01 * Double.parseDouble(t1.getText()))
                            * Double.parseDouble(t2.getText())
                            * Double.parseDouble(t3.getText());
                    t4.setText(String.valueOf(i
                            / (Double.parseDouble(t2.getText()) * 12)));
                    t5.setText(String.valueOf(i));
                } catch (Exception e2)
                {
                }
            }
        });

        add(p1);
        add(b1);
    }

    public static void main(String[] args)
    {
        LoanCalculator lc = new LoanCalculator();
        lc.setTitle("Loan Calculator");
        lc.setSize(300, 300);
        lc.setLocationRelativeTo(null);
        lc.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        lc.setVisible(true);

    }
}

你可能感兴趣的:(Java基础)