我想写个计算器:思路是,在一个窗口北面添加文本区,南面添加一个面板:panel,然后在这个面板里面添加两个面板panel_1,panel_2,这个两个面板的布局是GridLayout(5,2),然后在这个两个面板里面分别添加10个按钮。
上面是运行结构。
我想要的结构是:左边的按钮占满了panel_1,右边的按钮占满了panel_2
下面是代码:
import java.awt.*;
import java.awt.event.*;
class MyComputer extends Frame {
TextField text;
Panel panel_1,panel_2;
Button button[]=null;
Button _button[]=null;
MyComputer(String name){
super(name);
setBounds(10,10,500,400);
setLayout(new BorderLayout());
text=new TextField(100);
Panel panel=new Panel();
Panel panel_1=new Panel();
Panel panel_2=new Panel();
add(text,BorderLayout.NORTH);
//text.setBounds(0,0,500,50);
add(panel,BorderLayout.SOUTH);
//panel.setBounds(110,0,500,280);
panel.setLayout(new BorderLayout());
panel.add(panel_1,BorderLayout.WEST);
panel.add(panel_2,BorderLayout.EAST);
panel_1.setBounds(101,0,240,300);
panel_2.setBounds(101,0,240,300);
panel_1.setLayout(new GridLayout(5,2));//
panel_2.setLayout(new GridLayout(5,2));
button=new Button[10];
for(int i=0;i<=9;i++)//通过循环来构造10个数字按钮
{
button[i]=new Button(""+i);//将一个数字转换为字符型
//button[i].setSize((int)panel_1.getWidth()/5,(int)panel.getHeight()/2);
panel_1.add(button[i]);
}
//enum calculate_simbol{b}a;
String ch[]=new String[10];
ch[0]="=";
ch[1]="+";
ch[2]="-";
ch[3]="*";
ch[4]="/";
ch[5]="sqrt";
ch[6]="sin";
ch[7]="cos";
ch[8]="tan";
ch[9]="cot";
_button=new Button[10];
for(int j=0;j<10;j++)//*********这里如果是j<9就会有一个指针指向一个空的对象。就会产生空指针的异常************
{
_button[j]=new Button(ch[j]);
//_button[j].setSize((int)panel_2.getWidth()/5,(int)panel_2.getHeight()/2);
panel_2.add(_button[j]);
}
for(int k=0;k<10;k++)
{
button[k].addActionListener(new Monitor());
_button[k].addActionListener(new Monitor());
}
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){System.exit(0);}
});
setVisible(true);
panel_1.setVisible(true);
panel_2.setVisible(true);
validate();
}
}
class Monitor implements ActionListener{
public void actionPerformed(ActionEvent e){
}
}
public class TestComputer {
public static void main(String args[]){
MyComputer mc=new MyComputer("我的计算机器");
}
}