2 sinat 24245933 sinat_24245933 于 2014.12.05 15:28 提问

java初学者,老师要求做计算器。页面做好了,就是不知道怎么实现按钮的功能

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

public class JSQ extends JFrame{
private static final long serialVersionUID = -8568126884560298943L;

public JSQ(){
      Container C=getContentPane();

      result.setEnabled(false);
      result.setHorizontalAlignment(JTextField.RIGHT);
      result.setColumns(12);
      Font f=new Font("宋体",Font.BOLD,36);
      result.setFont(f);

      JButton clear=new JButton("CE");
      JButton point=new JButton(".");
      JButton count=new JButton("=");
      JButton add=new JButton("+");
      JButton sub=new JButton("—");
      JButton mul=new JButton("*");
      JButton div=new JButton("/");
      JButton back=new JButton("C");
      JButton electric=new JButton("ON/OFF");
      JButton music=new JButton("music");

      JButton[] button=new JButton[10];
      for(int i=0;i<=9;i++){
         button[i]=new JButton(""+i);
      }

      JPanel p=new JPanel();
      p.setLayout(new BorderLayout(0,0));
      p.add(result,BorderLayout.NORTH);
      p.setBorder(new EmptyBorder(5,5,5,5));

      JPanel p1=new JPanel();
      p1.setSize(210,250);
      p1.setLayout(new GridLayout(4,5,5,5));
      for(int i=9;i>=0;i--){
          p1.add(button[i]);
      }
      p1.add(point); 
      p1.add(back);
      p1.setBorder(new EmptyBorder(5,0,0,0));


      JPanel p2=new JPanel();
      p2.setLayout(new GridLayout(4,2,5,5));
      p2.setBorder(new EmptyBorder(5,0,0,0));
      p2.add(music); 
      p2.add(electric);
      p2.add(clear);
      p2.add(add);
      p2.add(sub);
      p2.add(mul);
      p2.add(div);
      p2.add(count);

      JPanel p3=new JPanel();
      p3.setLayout(new GridLayout(1,2,5,5));
      p3.add(p1);
      p3.add(p2);

      p.add(p3,BorderLayout.CENTER);
      C.add(p); 


}


public static void main(String[] args) {
      JSQ J=new JSQ();
      J.setTitle("计算器");
      J.setSize(420,300);
      J.setLocationRelativeTo(null);
      J.setDefaultCloseOperation(EXIT_ON_CLOSE);
      J.setVisible(true); 
}

}

5个回答

my_computer
my_computer   2014.12.05 15:53

Button应该有事件监听器,在事件监听器中应该有onclick方法,
当发生点击事件时执行onclick方法

CSDNJavaLiwei
CSDNJavaLiwei   2014.12.05 16:48

把那些按钮监听起来,将数据传到后台计算就行了。

CSDNJavaLiwei
CSDNJavaLiwei   2014.12.05 16:48

把那些按钮监听起来,将数据传到后台计算就行了。

u013704361
u013704361   2014.12.06 00:44

button监听,OnClickListener将数据传到后台计算,没有监听,点了button后没有处理啊

eagleyan
eagleyan   Rxr 2014.12.06 05:35

还在用Swing么,oracle已经抛弃swing了,看看java fx吧

http://www.oracle.com/technetwork/java/javase/overview/javafx-samples-2158687.html

Csdn user default icon
上传中...
上传图片
插入图片