Java Swing is a GUI (graphical user Interface) widget toolkit for Java. Java Swing is a part of Oracle’s Java foundation classes . Java Swing is an API for providing graphical user interface elements to Java Programs.Swing was created to provide more powerful anIn this article we will use Java Swing components to create a simple binary calculator with only 1,0,+, -, /, * flexible components than Java AWT (Abstract Window Toolkit).
public class binary calculator extends JFrame implements ActionListener{ private int size = 6; JPanel jp = null; JTextField jtf = null; JButton []jb = new JButton[size]; JButton jb1 = null,jb2 = null,jb3 = null; JPanel jp1 = null; public static void main(String[] args) { // TODO Auto-generated method stub calculator d = new calculator(); } public calculator() { jtf = new JTextField(); jp = new JPanel(); jb[4] = new JButton("-"); jb[0] = new JButton("CE"); jb[1] = new JButton("0"); jb[2] = new JButton("1"); jb[3] = new JButton("+"); jb[5] = new JButton("="); for(int i = 0;i < size;i ++){ jp.add(jb[i]); jb[i].addActionListener(this); } jp.setLayout(new GridLayout(5,4,10,10)); this.add(jp); this.add(jtf,BorderLayout.NORTH); this.setTitle("計算器"); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //設置窗體居中顯示 this.setLocationRelativeTo(null); //禁止改變窗體大小 this.setResizable(false); this.setSize(400,300); this.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub if(e.getSource() == jb[0]){ //清屏 jtf.setText(""); } else if(e.getSource() == jb[1]){ String str = jtf.getText(); str += "0"; jtf.setText(str); } else if(e.getSource() == jb[2]){ String str = jtf.getText(); str += "1"; jtf.setText(str); } else if(e.getSource() == jb[3]){ String str = jtf.getText(); str += "+"; jtf.setText(str); } /* * 若為等的時候,計算式子的結果,運算結果為+ - * / %四種方法得到 */ else if(e.getSource() == jb[5]){ String str = jtf.getText(); char[] ss = str.toCharArray(); String s1 = "",s2 = ""; char cc = 0; //獲取運算符 int i; for(i = 0;i < ss.length;i ++) if(ss[i] =='+'|| ss[i] == '-' || ss[i] == '*' || ss[i] == '/' || ss[i] == '%'){ cc = ss[i]; break; } else s1 += String.valueOf(ss[i]); for( ++ i;i < ss.length;i ++) s2 += String.valueOf(ss[i]); double[]a = new double[2]; String g=Integer.valueOf(s1,2).toString(); String g1=Integer.valueOf(s2,2).toString(); a[0] = Double.parseDouble(g); a[1] = Double.parseDouble(g1); /* double c,b=1,total=0,c2,b2=1,total2=0; while ( a[0] >= 0 ) { c = ( a[0] % 2 ) * b; a[0] = a[0] / 10; b = b * 2; total = total + c; if ( a[0] == 0 ) { break; } } while ( a[1] >= 0 ) { c2 = ( a[1] % 2 ) * b2; a[1] = a[1] / 10; b2 = b2 * 2; total2 = total2 + c2; if (a[1] == 0 ) { break; } }*/ double m = 0.0; if(cc == '+') m = a[0] + a[1]; else if(cc == '-') m = a[0]- a[1]; str += " = " + String.valueOf(m); jtf.setText(str); } else if(e.getSource() == jb[4]){ String str = jtf.getText(); str += "-"; jtf.setText(str); } } }