日期:2014-05-20  浏览次数:20688 次

求改,JAVA做一个加法计算器,按钮触发
[code=Java][/code]import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Container;
import java.awt.BorderLayout;
import java.awt.*;
import javax.swing.*;

public class Jisuan extends JFrame
{
  public Jisuan()
  {
  super("SUM");
  Container c = getContentPane( );
  c.setLayout(new FlowLayout( ));
  JTextField a1=new JTextField(" ", 4);
  JLabel a0=new JLabel("+");
  JTextField a2=new JTextField(" ", 4);
  c.add(a1); c.add(a0); c.add(a2);
  JButton b=new JButton("=");
  c.add(b);
  JTextField a3=new JTextField(" ", 4);
  c.add(a3);
  b.addActionListener(new ActionListener()
  { 
  public void actionPerformed(ActionEvent e)  
  {
  JTextField a1=new JTextField(" ", 4);
  String s1=a1.getText();
  JTextField a2=new JTextField(" ", 4);
  String s2=a2.getText();
  double d1=Double.parseDouble(s1);
  double d2=Double.parseDouble(s2);
  double d3=d1+d2;
  String s3=Double.toString(d3);
  JTextField a3=new JTextField(" ", 4);
  a3.setText(s3);
 
  /*int [ ] i=new int[2];
  int [0]=Integer.parseInt(a[1].getText());
  int [1]=Integer.parseInt(a[2].getText());
  if(e.getSource()==b)  
  a[3].setText(String.valueOf(i[0]+i[1]));*/
  }
  }
  );
  }

public static void main(String args[])
  {
  JFrame app = new JFrame();
  app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  app.setSize( 320, 120 );
  app.setVisible(true);
  }
}


------解决方案--------------------
Java code

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class Jisuan extends JFrame {
    JTextField a1;  //把这些当做成员变量
    JTextField a2;
    JButton b;
    JTextField a3;
    public Jisuan() {
        super("SUM");
        Container c = getContentPane();
        c.setLayout(new FlowLayout());
        a1 = new JTextField(" ", 4);
        JLabel a0 = new JLabel("+");
        a2 = new JTextField(" ", 4);
        c.add(a1);
        c.add(a0);
        c.add(a2);
        b = new JButton("=");
        c.add(b);
        a3 = new JTextField(" ", 4);
        c.add(a3);
        b.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //这里面就不要定义哪些文本框了,
                String s1 = a1.getText();
                String s2 = a2.getText();
                double d1 = Double.parseDouble(s1);
                double d2 = Double.parseDouble(s2);
                double d3 = d1 + d2;
                String s3 = Double.toString(d3);
                a3.setText(s3);

            }
        });
    }

    public static void main(String args[]) {
        Jisuan app = new Jisuan(); //注意这个地方错了
        app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        app.setSize(320, 120);
        app.setVisible(true);
    }
}