e.getActionCommand()和(JButton)e.getSource()

这两个方法初见于画板的设计实验中

完整代码 : if("".equals(e.getActionCommand())) {
            JButton jb=(JButton)e.getSource();//
            color=jb.getBackground();
            nowColor.setBackground(color);
        }else {
            str=e.getActionCommand();
        }

e.getActionCommand()用于判断按下按钮时获取的字符串是不是空,是空则是选择颜色按钮

e.getSource()获取按钮所产生的事件,返回类型为对象,需强转型为Button

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 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、付费专栏及课程。

余额充值