我最终大大简化了我的方法。我只是修改了第二个类文件来获取按钮,并完全摆脱了第三个文件。现在操作按钮和按下键盘上的返回键都会导致程序完成计算。这确实不难,只需要使用相同的方法,但需要使用不同类型的侦听器。谢谢!创建执行功能的按钮
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));
}
}
}
*“但第三个是我需要一些指导的地方”*嗯......“提出问题”。那对于指导如何?此外,为了更快提供更好的帮助,请发布[SSCCE](http://sscce.org/)。 –
好点。下次会做。感谢您的链接。 – Lou44