图形用户界面(一)GUI元素之文本域

 这是一个展示文本域使用的小程序。
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));
    }
  }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值