import java.awt.GridLayout;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JPanel;import javax.swing.JTextField;import java.awt.BorderLayout;class Calculator extends JFrame{private JPanel pan= new JPanel();private JButton button;private JTextField text;String number[]={"7","8","9","/","4","5","6","*","1","2","3","-","0",".","=","+"};public Calculator() {super("小神童计算器");setSize(600,600);setLayout(new BorderLayout(5,5));setVisible(true);text=new JTextField("请输入数字",20);pan.setLayout(new GridLayout(4,4));for(int i=0;i<12;i++){button=new JButton(number[i]);pan.add(button);}pan.setVisible(true);//add(text,BorderLayout.NORTH);add(pan,BorderLayout.CENTER);setDefaultCloseOperation(EXIT_ON_CLOSE);}}public class test {public static void main(String [] args){Calculator cal=new Calculator();}}
2 回答
慕码人8056858
TA贡献1803条经验 获得超6个赞
把setVisible(true);这句移到public Calculator()构造函数的末尾,按钮就显示出来了,
另外for(int i=0;i<12;i++)应该改成for(int i=0;i<16;i++)因为你有16个按钮
完整的Java程序如下(改动的地方见注释)
import java.awt.GridLayout; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextField; import java.awt.BorderLayout; class Calculator extends JFrame{ private JPanel pan= new JPanel(); private JButton button; private JTextField text; String number[]={ "7" , "8" , "9" , "/" , "4" , "5" , "6" , "*" , "1" , "2" , "3" , "-" , "0" , "." , "=" , "+" }; public Calculator() { super ( "小神童计算器" ); setSize( 600 , 600 ); setLayout( new BorderLayout( 5 , 5 )); text= new JTextField( "请输入数字" , 20 ); pan.setLayout( new GridLayout( 4 , 4 )); for ( int i= 0 ;i< 16 ;i++){ //这里i<12;改成i<16; button= new JButton(number[i]); pan.add(button); } pan.setVisible( true ); //add(text,BorderLayout.NORTH); add(pan,BorderLayout.CENTER); setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible( true ); //这里把setVisible(true);移到这里 } } public class test { public static void main(String [] args){ Calculator cal= new Calculator(); } } |
运行结果
添加回答
举报
0/150
提交
取消