为了账号安全,请及时绑定邮箱和手机立即绑定

我是想写一个计算器的面板,请问该怎么办?

我是想写一个计算器的面板,请问该怎么办?

繁花不似锦 2022-10-07 12:15:53
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(); }}

运行结果


查看完整回答
反对 回复 2022-10-12
?
繁星淼淼

TA贡献1775条经验 获得超11个赞


查看完整回答
反对 回复 2022-10-12
  • 2 回答
  • 0 关注
  • 96 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信