我最终大大简化了我的方法。我刚刚将第二个类文件修改为按钮并完全摆脱了第三个。现在,操作按钮和键盘上的返回键都会导致程序完成计算。这真的不难,只需要使用相同的方法但使用不同类型的侦听器。谢谢!
import javax.swing.JFrame;
public class Fahrenheit
{
public static void main (String[] args)
{
JFrame frame = new JFrame ("Fahrenheit");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FahrenheitPanel panel = new FahrenheitPanel();
frame.getContentPane().add(panel);
frame.pack();frame.setVisible(true);
}
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FahrenheitPanel extends JPanel
{
private JLabel inputLabel, outputLabel, resultLabel;
private JTextField fahrenheit;
private JButton push;
public FahrenheitPanel()
{
inputLabel = new JLabel ("Enter Fahrenheit temperature:");
outputLabel = new JLabel ("Temperature in Celsius: ");
resultLabel = new JLabel ("---");
push = new JButton ("Convert");
fahrenheit = new JTextField (5);
fahrenheit.addActionListener (new TempListener());
push.addActionListener (new ButtonListener());
add (inputLabel);
add(fahrenheit);
add (outputLabel);
add (resultLabel);
add (push);
setPreferredSize (new Dimension(300,75));
setBackground (Color.yellow);
}
private class TempListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
int fahrenheitTemp, celsiusTemp;
String text = fahrenheit.getText();
fahrenheitTemp = Integer.parseInt (text);
celsiusTemp = (fahrenheitTemp-32) * 5/9;
resultLabel.setText (Integer.toString (celsiusTemp));
}
}
private class ButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
int fahrenheitTemp, celsiusTemp;
String text = fahrenheit.getText();
fahrenheitTemp = Integer.parseInt (text);
celsiusTemp = (fahrenheitTemp-32) * 5/9;
resultLabel.setText (Integer.toString (celsiusTemp));
}
}
}