import java.awt.*; import java.awt.event.*; import java.util.*;//?? import javax.swing.*;// J class Calculate { static JTextField tx1; static JTextField tx2; static JTextField tx3; static JPanel p; static JComboBox cho; void init() { JFrame f=new JFrame("calculate"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//JFrame可以关闭 Label lab=new Label("计算器举例"); tx1=new JTextField("",new Integer(5)); tx2=new JTextField("",new Integer(5)); tx3=new JTextField("",new Integer(5)); cho=new JComboBox(); cho.addItem("+"); cho.addItem("-"); cho.addItem("*"); cho.addItem("/"); JButton b=new JButton("="); b.addActionListener(new MyActionListener()); p = new JPanel(); p.setLayout(new FlowLayout()); p.add(tx1); p.add(cho); p.add(tx2); p.add(b); p.add(tx3); Container c=f.getContentPane();//获取当前框架的容器; c.setLayout(new BorderLayout()); c.add(lab,BorderLayout.NORTH); c.add(p,BorderLayout.CENTER); f.pack();//将框架按需缩小,使其紧凑; f.setVisible(true); } public static void main(String[] args) { Calculate cal=new Calculate(); cal.init(); } } class MyActionListener implements ActionListener{ public void actionPerformed(ActionEvent e) { int a=Integer.parseInt(Calculate.tx1.getText().trim()); int b=Integer.parseInt(Calculate.tx2.getText().trim()); int sel=Calculate.cho.getSelectedIndex(); int c=0; switch(sel) { case 0: c=a+b;break; case 1: c=a-b;break; case 2: c=a*b;break; case 3: c=a/b;break; } String d=(new Integer(c)).toString();//将整数包装成类,创建的对象就可以调用函数 Calculate.tx3.setText(d); } }
注: calculate.java使用了未经检查或不安全的操作。 注: 有关详细信息, 请使用 -Xlint:unchecked 重新编译。