java Swing GUI 入门-简易货币计算器

java Swing GUI 入门-简易货币计算器

觉得有用的话,欢迎一起讨论相互学习~

我的微博我的github我的B站

设计布局

  1. JcomboBox下拉框
  2. JTextField的不可编辑的属性
  3. 可以通过调节一个控件的Vertical Align属性以调节一个元素的位置,特别是将其设置为top可以将这个控件调得较高,默认为center
  • 大概就这样:

注意一定不要选中Custom Create

  • 对于 ComboBox 控件,单击model属性

添加事件操作

添加下拉框事件

  • 为了使下拉框变化时,JLabel中的值也能相应的变化,向下拉框添加动作监听器.
    public CurrencyConverter() {
        comboBox1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                moneyTypeLabel.setText(" "+comboBox1.getSelectedItem());
            }
        });
    }//end CurrencyConverter()
  • 添加main函数,右键添加

添加按钮事件

  • 思路:点击这个按钮之后将前一个TextField中的值读取出来乘以其和JCombox中国家币种得汇率,得到的结果输出到第二个TextField中.
        convertButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                double[] rates = {0.1253, 15.7953, 0.1527};//Eurc,Yen,U.S.dollar
                double selectedRate = rates[comboBox1.getSelectedIndex()];
                double converted = Double.parseDouble(canadianField.getText()) * selectedRate;
                convertedField.setText(" " + converted + " in " + comboBox1.getSelectedItem());
            }
        });

程序演示

完整代码

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class CurrencyConverter {
    private JPanel mainPanel;
    private JPanel topPanel;
    private JPanel bottomPanel;
    private JTextField canadianField;
    private JComboBox comboBox1;
    private JButton convertButton;
    private JTextField convertedField;
    private JLabel moneyTypeLabel;

    public CurrencyConverter() {
        comboBox1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                moneyTypeLabel.setText(" " + comboBox1.getSelectedItem());
            }
        });
        convertButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                double[] rates = {0.1253, 15.7953, 0.1527};//Eurc,Yen,U.S.dollar
                double selectedRate = rates[comboBox1.getSelectedIndex()];
                double converted = Double.parseDouble(canadianField.getText()) * selectedRate;
                convertedField.setText(" " + converted + " in " + comboBox1.getSelectedItem());
            }
        });
    }//end CurrencyConverter()

    public static void main(String[] args) {
        JFrame frame = new JFrame("Currency Converter");
        frame.setContentPane(new CurrencyConverter().mainPanel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }
}//end class

posted @ 2020-12-21 15:45  WUST许志伟  阅读(251)  评论(0编辑  收藏  举报