问题描述
我想写一个计算器练习swing,用网格组布局管理器,可是发现按钮不能充满画面,下面是我swing部分的代码麻烦各位给点建议importjavax.swing.*;importjava.awt.*;importjava.awt.event.*;importjava.lang.reflect.InvocationHandler;importjava.lang.reflect.Method;publicclassAAextendsJFrame{Monitori;//屏幕显示器JButtonbb;//退格键JButtonbc;//清零键JButtonb[];//1到9键GridBagHelpg[];//为1到9键添加布局使用JButtonb0;//添加0键JButtonbd;//添加等号JButtonbp;//添加小数点JButtonbr;//添加除号JButtonbm;//添加乘号JButtonba;//添加加号JButtonbs;//添加减号AA(){JPanelpp=newJPanel();//设置框架主体pp.setLayout(newBorderLayout());add(pp);setSize(300,300);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);i=newMonitor();//第18,19行是为计算器添加屏幕pp.add(i,BorderLayout.NORTH);JPanelp1=newJPanel();pp.add(p1,BorderLayout.CENTER);p1.setLayout(newGridBagLayout());bc=newJButton("C");//添加清零键GridBagHelph1=newGridBagHelp(0,0,2,1);p1.add(bc,h1);bb=newJButton("Backspace");//添加退格键GridBagHelph2=newGridBagHelp(2,0,2,1);p1.add(bb,h2);b=newJButton[9];//添加0到9按键g=newGridBagHelp[9];intx=0;inty=1;for(inti=0;i<9;i++){Integerq=newInteger(i+1);b[i]=newJButton(q.toString());g[i]=newGridBagHelp(x,y,1,1);p1.add(b[i],g[i]);if(x==2){x=0;y++;}else{x++;}}b0=newJButton("0");//添加0键GridBagHelpg0=newGridBagHelp(0,4,1,1);p1.add(b0,g0);bp=newJButton(".");//添加0键GridBagHelpgp=newGridBagHelp(1,4,1,1);p1.add(bp,gp);bd=newJButton("=");//添加=键GridBagHelpgd=newGridBagHelp(2,4,1,1);p1.add(bd,gd);br=newJButton("/");//添加/键GridBagHelpgr=newGridBagHelp(3,1,1,1);p1.add(br,gr);bm=newJButton("*");//添加*键GridBagHelpgm=newGridBagHelp(3,2,1,1);p1.add(bm,gm);bs=newJButton("-");//添加-键GridBagHelpgs=newGridBagHelp(3,3,1,1);p1.add(bs,gs);ba=newJButton("+");//添加+键GridBagHelpga=newGridBagHelp(3,4,1,1);p1.add(ba,ga);setVisible(true);}publicvoidaddButton(){}publicstaticvoidmain(Stringa[]){newAA();}}classMonitorextendsJTextField{Monitor(){setHorizontalAlignment(JTextField.RIGHT);setFocusable(false);}}classGridBagHelpextendsGridBagConstraints{//本类是网格组管理器扩展类publicGridBagHelp(intgridx,intgridy){this.gridx=gridx;this.gridy=gridy;this.fill=GridBagConstraints.BOTH;}publicGridBagHelp(intgridx,intgridy,intgridwidth,intgridheight){this.gridheight=gridheight;this.gridwidth=gridwidth;this.gridx=gridx;this.gridy=gridy;}}
解决方案
解决方案二:
up...
解决方案三:
使用布局,比如BoardLayout它会自动填满框架的