36.微改进的计算器,JComboBox下拉框

  • 类 JComboBox: 下拉框
    getSelectedItem();//返回下拉框当前选项
public class SwingTest2 {

    public static void main(String[] args) {
        JFrame jFrame = new JFrame("计算器");

        jFrame.setLayout(null );//绝对布局      
        final JTextField nub1Txt = new JTextField();
        final JTextField nub2Txt = new JTextField();
        final JTextField nub3Txt = new JTextField();
        JButton jB = new JButton("=");
        //JLabel fuHao =new JLabel("+" ,JLabel.CENTER); 
        String fuHao[] = {"+", "-", "*", "/"}; 
        final JComboBox jcb = new JComboBox(fuHao);//下拉框,**注意**参数为fuHao非fuHao[]

        nub1Txt.setBounds(10, 30,40,25);//绝对布局,组件摆放位置和大小
        //fuHao.setBounds(80,40 , 10, 10);
        jcb.setBounds(60,30 ,40, 25);
        nub2Txt.setBounds(110, 30,50,25);//绝对布局,组件摆放位置和大小
        jB.setBounds(170, 30, 50, 25);
        nub3Txt.setBounds(230, 30, 50, 25);

        //匿名监听类
        jB.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent arg0) {
                // TODO 自动生成的方法存根
                String nub1 = nub1Txt.getText();//获取数字文本
                String nub2 = nub2Txt.getText();//获取数字文本
                String  algorithm = (String) jcb.getSelectedItem();//返回下拉框当前选项
                int result = 0;//结果必须定义在这里,无法定义在if{}内,因为变量作用域的问题
                if(algorithm.equals("+")){
                    result = Integer.parseInt(nub1) + Integer.parseInt(nub2);
                }
                else if(algorithm.equals("-")){
                    result = Integer.parseInt(nub1) - Integer.parseInt(nub2);
                }
                else if (algorithm.equals("*")){
                    result = Integer.parseInt(nub1) * Integer.parseInt(nub2);
                }
                else if (algorithm.equals("/")){
                    result = Integer.parseInt(nub1) / Integer.parseInt(nub2);
                }
                //int result = Integer.parseInt(nub1) + Integer.parseInt(nub2);
                nub3Txt.setText(String.valueOf(result));//显示文本
                //nub3Txt.setText(result + "");//(result + "")与(String.valueOf(result)同效果,将int类型转换成String
            }
        });

        jFrame.add(nub1Txt);
        //jFrame.add(fuHao);
        jFrame.add(jcb);
        jFrame.add(nub2Txt);
        jFrame.add(jB);
        jFrame.add(nub3Txt);

        jFrame.setLocation(300, 200);
        jFrame.setSize(300, 150);
        jFrame.setVisible(true);//让容器显示
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

你可能感兴趣的:(JAVA)