java - 如何使用带有 Action 监听器的方法?

标签 java swing user-interface actionlistener

我的程序运行并弹出窗口,但当用户单击 converToF 按钮的 convertoC 时,它不会评估将用户输入转换为 *c 或 *f 的计算。我试图将代码放在单独的 Action 监听器中,但出现错误。它在逻辑上看起来是正确的,但也许我将一些代码放错了地方。谁能帮帮我?

package edu.westga.TemperatureConverter.controller;

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

/**
 * 
 * @author
 * 
 */
public class Temperature extends JFrame {
    private double fahrenheit;
    private double celsius;
    private JButton fahrenheitButton;
    private JButton celsiusBUtton;
    private JTextField textBox;
    private JLabel instructions;
    private FlowLayout layout;
    private Container container;
    private JButton clearButton;
    private JLabel results;

    /**
     * Temperature constructor
     */
    public Temperature() {
        super("temperature converter");
        this.layout = new FlowLayout();
        this.container = getContentPane();
        setLayout(this.layout);

        TemperatureConverter convertemp = new TemperatureConverter();
        this.instructions = new JLabel("please enter the Temperture:");
        add(this.instructions);
        this.textBox = new JTextField(10);
        add(this.textBox);
        this.textBox.addActionListener(convertemp);

        this.fahrenheitButton = new JButton(" convert to Fahrenheit");
        add(this.fahrenheitButton);
        // fahrenheitButton.addActionListener(new ActionListener() {
        // public void actionPerformed(ActionEvent event) {
        //
        // convertToC();
        // }
        // });

        this.celsiusBUtton = new JButton("convert to Celsius ");
        add(this.celsiusBUtton);
        // celsiusBUtton.addActionListener(new ActionListener() {
        // public void actionPerformed(ActionEvent event) {
        // String text = "";
        // double num = 0;
        // if (event.getSource() == celsiusBUtton) {
        // num = Double.parseDouble(text);
        // convertToC(num);
        // results.setText("your aswer was converted to:" + num);
        // }}
        // });

        this.clearButton = new JButton(" clear");
        add(this.clearButton);
        // clearButton.addActionListener(new ActionListener() {
        // public void actionPerformed(ActionEvent event) {
        //
        // convertToC();
        // }
        // });

        this.results = new JLabel("your aswer was converted to: ");
        add(this.results);
    }

    /**
     * convert to celsius
     * 
     * @param num
     *            user input number
     * @return converted answer the answer
     */
    public double convertToC(double num) {
        this.fahrenheit = num;
        double convertedAnswer;
        convertedAnswer = 5.0 / 9.0 * (this.fahrenheit - 32);
        return convertedAnswer;
    }

    /**
     * Convert to fahrenheit
     * 
     * @param num
     *            user input number
     * @return converted answer the answer
     */
    public double convertToF(double num) {
        this.celsius = num;
        double convertedAnswer;
        convertedAnswer = (32 + 5 / 9) * this.celsius;
        return convertedAnswer;
    }

    /**
     * clears the window of previous numbers
     */
    public void clear() {

    }

    /**
     * anonymous class that activates the conversion of the users input
     * 
     * @author
     * @version
     * 
     */
    public class TemperatureConverter implements ActionListener {

        public void actionPerformed(ActionEvent event) {
            String text = "";
            double num = 0;
            if (event.getSource() == celsiusBUtton) {
                num = Double.parseDouble(text);
                convertToC(num);
                results.setText("your answer was converted to:" + num + "C");
            } else {
                if (event.getSource() == fahrenheitButton) {
                    num = Double.parseDouble(text);
                    convertToF(num);
                    results.setText("your answer was converted to:" + num + "F");
                }
            }
        }

    }
}

最佳答案

这里有一些错误:

1) 您没有将计算值保存在 ActionListener

if (event.getSource() == celsiusBUtton) {
      num = Double.parseDouble(text);
      num = convertToC(num);
      results.setText("your answer was converted to:" + num + "C");
} else {
      if (event.getSource() == fahrenheitButton) {
           num = Double.parseDouble(text);
           num = convertToF(num);
           results.setText("your answer was converted to:" + num + "F");
      }
}

2) 您没有将 Action 监听器绑定(bind)到您的按钮。

this.fahrenheitButton = new JButton(" convert to Fahrenheit");
this.fahrenheitButton.addActionListener(convertemp);  // make them do something!!
add(this.fahrenheitButton);


this.celsiusBUtton = new JButton("convert to Celsius ");
this.celsiusBUtton.addActionListener(convertemp);  // make them do something!!
add(this.celsiusBUtton);

3) 在你的 actionlistener 中,你的文本总是 "",这会给你一个 NumberFormatException 从你的文本框中获取文本,你应该可以开始了(尽管你会想要做比这更多的错误检查......)

public void actionPerformed(ActionEvent event) {
    String text = textBox.getText();  // you need to get the text from the text box
    double num = 0;
    if (event.getSource() == celsiusBUtton) {
          num = Double.parseDouble(text);
          num = convertToC(num);
          results.setText("your answer was converted to:" + num + "C");
    } else {
        if (event.getSource() == fahrenheitButton) {
              num = Double.parseDouble(text);
              num = convertToF(num);
              results.setText("your answer was converted to:" + num + "F");
        }
    }
}

我可能还应该指出,ActionListener 不会监听其他小部件对您放置它的对象所做的操作,它正在监听 那个小部件上的操作.您已将它放置在文本框上,这将使监听器监听文本框上的事件,而不是按钮上的事件。如果用户愿意,您的方法可能有助于捕获“Enter”键或其他东西。

关于java - 如何使用带有 Action 监听器的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24854245/

相关文章:

java - Android 计时器不添加秒数

java - 如何使用jackson在java中将json转换为POJO

java - 在单个单元格上应用 TableCellRenderer

gwt - 是否可以跨越单元表 GWT 的 header

python - 为什么我无法将条目小部件中的字符串转换为 float ?

javascript - React DIV动态布局算法创建盒中盒 View

java - 在 hibernate 的任何领域

java - 仅使用 MySQL 存储过程和 Java 构建图书馆管理系统

java - JComboBox - 缩短按键监听器

java - JTable 中 JComboBox 中的对象与组合列表中的同一对象不关联