public class Nacci extends JFrame implements ActionListener { int i=0; private JTextField display,status; private JButton[] b; private JPanel p2; String arr[]={"1","2","3","4","5","6","7","8","9","*","0","#"};
public Nacci() { display=new JTextField(20); status=new JTextField(20); p2=new JPanel(); p2.setLayout(new GridLayout(4,3)); for(i=0;i<12;i++) { b[i]=new JButton(arr[i]); p2.add(b[i]); b[i].addActionListener(this); } display.setEditable(false); this.setTitle("Natsumi Abe"); this.getContentPane().add(display,BorderLayout.NORTH); this.getContentPane().add(p2,BorderLayout.CENTER); this.getContentPane().add(status,BorderLayout.SOUTH); this.setSize(250,250); this.setVisible(true); } public void actionPerformed(ActionEvent evt) { if(evt.getSource()==b[10]) display.setText("*"); else if(evt.getSource()==b[11]) display.setText("0"); else if(evt.getSource()==b[12]) display.setText("#"); } public static void main(String args[]) { new Nacci(); } }
----------------解决方案--------------------------------------------------------
import javax.swing.*; import java.awt.event.*; import java.awt.*; public class Nacci extends JFrame implements ActionListener { int i=0; private JTextField display,status; private JButton[] b=new JButton[12]; private JPanel p2; String arr[]={"1","2","3","4","5","6","7","8","9","*","0","#"};
public Nacci() { display=new JTextField(20); status=new JTextField(20);
p2=new JPanel();
p2.setLayout(new GridLayout(4,3)); for(i=0;i<12;i++) { b[i]=new JButton(arr[i]); p2.add(b[i]); b[i].addActionListener(this); } display.setEditable(false); this.setTitle("Natsumi Abe"); this.getContentPane().add(display,BorderLayout.NORTH); this.getContentPane().add(p2,BorderLayout.CENTER); this.getContentPane().add(status,BorderLayout.SOUTH); this.setSize(250,250); this.setVisible(true); }
public void actionPerformed(ActionEvent evt) { if(evt.getSource()==b[10]) display.setText("*"); else if(evt.getSource()==b[11]) display.setText("0"); else if(evt.getSource()==b[12]) display.setText("#"); }
public static void main(String args[]) { new Nacci(); } }
----------------解决方案--------------------------------------------------------
建议你先自己看看关于数组的那章。
千万别忘记,数组要初始化。
基础知识不牢靠阿!
----------------解决方案--------------------------------------------------------
//这里还要改改 public void actionPerformed(ActionEvent evt) { if( evt.getSource()==b[9] ) display.setText("*"); else if( evt.getSource()==b[10] ) display.setText("0"); else if( evt.getSource()==b[11] ) display.setText("#"); }
----------------解决方案--------------------------------------------------------
谢谢。。一定把知识补上
----------------解决方案--------------------------------------------------------
数组下标超了是从0开始的到11
并要在声明时初始化大小
----------------解决方案--------------------------------------------------------