这是一个展示文本域使用的小程序。
Fahrenheit显示一个GUI窗口,其中一个文本域,可以键入Fahrenheit(华氏)温度。当按回车键时,显示对应的Celsius(摄
氏)温度。当按回车键时,显示对应的Celsius(摄氏)温度。
当按下回车时(且光标在文本域中),文本域产生动作事件。所以需要设置一个监听器对象来响应动作事件,这与前面的例子是类似的。
注意,按钮和文本域产生同一类的事件——动作事件。所以Fahrenheit程序也可以重新设计:向GUI中添加一个JButton对象,当按下按钮时,用用这个对象完成温度的转换。这种情况下,可用同一个监听器在同一时刻监听多个组件。所以监听器必须添加到文本域及按钮上,这样就可以使用两种输入方式了。
效果如图:
Fahrenheit.java
import javax.swing.JFrame;
public class Fahremheit {
//创建一个温度转换GUI
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);
}
}
FahrenheitPanel.java
import java.awt.Color;
import .......
public class FahrenheitPanel extends JPanel {
private JLabel inputLabel, outputLabel, resultLabel;
private JTextField fahrenheit;
public FahrenheitPanel(){
inputLabel = new JLabel("Enter Fahrenheit temperature: ");
outputLabel = new JLabel("Temperature in Celsius: ");
resultLabel = new JLabel("----");
fahrenheit = new JTextField(5);
fahrenheit.addActionListener(new TempListener());
add(inputLabel);
add(fahrenheit);
add(outputLabel);
add(resultLabel);
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));
}
}
}