猿问

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

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();
}
}

繁花不似锦
浏览 97回答 2
2回答

慕码人8056858

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

繁星淼淼

随时随地看视频慕课网APP

相关分类

Java
JavaScript
我要回答