e.getSource()方法和e.getActionCommand()方法(转)

e.getSource()方法依赖于事件对象。

比如:JButton jbt = new JButton("button");中事件对象就是jbt

e.getActionCommand()方法依赖于按钮上的字符串

比如:JButton jbt = new JButton("button");中字符串button

简而言之:用e.getSource()得到的是jbt,而用e.getActionCommand()得到的是button。

  • 7
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
优化这段代码import javax.swing.*; import java.awt.*; import java.awt.event.*; public class TemperatureConverter implements ActionListener { private JFrame frame; private JPanel panel; private JLabel Label1,Label2; private JTextField Field1,Field2; private JButton Button1,Button2,Button3; public TemperatureConverter() { frame = new JFrame("温度换"); f.setSize ( 400,200 ) ; f.setVisible ( true ) ; f.setLocationRelativeTo ( null ) ; panel = new JPanel(); Label1 = new JLabel("摄氏度:"); Label2 = new JLabel("华氏度:"); Field1 = new JTextField(10); Field2 = new JTextField(10); Button1 = new Button("摄氏度 → 华氏度"); Button2 = new Button("华氏度 → 摄氏度"); Button3 = new Button("清空"); panel.add(Label1); panel.add(Label2); panel.add(Field1); panel.add(Field2); panel.add(Button1); panel.add(Button2); panel.add(Button3); Button1.addActionListener(this); Button2.addActionListener(this); Button3.addActionListener(this); public void actionPerformed(ActionEvent e) { if (e.getSource() == Button1) { double value = Double.parseDouble(Field1.getText()); double result = (value * 9 / 5) + 32; Field1.setText(String.format("%.2f", result)); } if (e.getSource() == Button2) { double value = Double.parseDouble(Field2.getText()); double result = (value - 32) * 5 / 9; Field1.setText(String.format("%.2f", result)); } if(e.getActionCommand().equals("清空") ) { Field1.setText(null); Field2.setText(null); } } } } public static void main(String[] args) { new TemperatureConverter(); }
最新发布
05-24
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值