日期:2014-05-20 浏览次数:20754 次
import java.awt.*; import javax.swing.*; import javax.swing.event.CaretEvent; import javax.swing.event.CaretListener; import javax.swing.event.DocumentListener; import java.text.NumberFormat; import javax.swing.event.DocumentEvent; import java.awt.event.ItemListener; import java.awt.event.ItemEvent; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; public class WangPeng extends JFrame { private static final String[] calculate = {"+","-","*","/"}; private JFormattedTextField text_1,text_2,text_3; private NumberFormat formatter = NumberFormat.getIntegerInstance(); private JComboBox combox_char; public WangPeng() { super("整数的算术运算"); this.setBackground(java.awt.Color.lightGray); this.setDefaultCloseOperation(EXIT_ON_CLOSE); this.getContentPane().setLayout(new FlowLayout()); text_1 = new JFormattedTextField(formatter); text_1.setColumns(10); text_1.setValue(Long.valueOf(0)); this.getContentPane().add(text_1); combox_char=new JComboBox(calculate); this.getContentPane().add(combox_char); text_2 = new JFormattedTextField (formatter); text_2.setValue(Long.valueOf(0)); text_2.setColumns(10); this.getContentPane().add(text_2); this.getContentPane().add(new JLabel("=")); text_3 = new JFormattedTextField (formatter); text_3.setColumns(10); text_3.setEditable(false); this.getContentPane().add(text_3); this.pack(); this.setVisible(true); xxxxxxx(); } private void xxxxxxx(){ FocusListener listener = new FocusListener(){ @Override public void focusGained(FocusEvent e){ compute(); } @Override public void focusLost(FocusEvent e){ compute(); } }; text_1.addFocusListener(listener); text_2.addFocusListener(listener); text_3.addFocusListener(listener); combox_char.addItemListener(new ItemListener(){ public void itemStateChanged(ItemEvent e){ compute(); } }); } private void compute(){ long n1 = ((Long)text_1.getValue()).longValue(); long n2 = ((Long)text_2.getValue()).longValue(); switch (combox_char.getSelectedIndex()) { case 0: text_3.setValue(Long.valueOf(n1+n2)); break; case 1: text_3.setValue(Long.valueOf(n1-n2)); break; case 2: text_3.setValue(Long.valueOf(n1*n2)); break; case 3: if (n2 != 0) { text_3.setValue(Long.valueOf(n1/n2)); } break; default: break; } } public static void main(String args[]) { java.awt.EventQueue.invokeLater(new java.lang.Runnable(){ @Override public void run(){ new WangPeng(); } }); } }