源代码如下
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
public class GridBagLayoutDemo extends JFrame implements ActionListener{
public GridBagLayoutDemo(){
GridBagLayout gridbag=new GridBagLayout();//创建网格包对象
GridBagConstraints c=new GridBagConstraints();//创建约束条件对象
this.setLayout(gridbag);
c.fill=GridBagConstraints.BOTH;//组件充满显示区域
c.gridwidth = 0;
makeButton("0", gridbag, c);
c.weighty = 1;
c.weightx = 1;
c.gridwidth = 1;
makeButton("1", gridbag, c);
makeButton("2", gridbag, c);
makeButton("3", gridbag, c);
c.gridwidth = GridBagConstraints.REMAINDER;
makeButton("+", gridbag, c);
c.gridwidth = 1;
makeButton("4", gridbag, c);
makeButton("5", gridbag, c);
makeButton("6", gridbag, c);
c.gridwidth = GridBagConstraints.REMAINDER;
makeButton("-", gridbag, c);
c.gridwidth = 1;
makeButton("7", gridbag, c);
makeButton("8", gridbag, c);
makeButton("9", gridbag, c);
c.gridwidth = GridBagConstraints.REMAINDER;
makeButton("*", gridbag, c);
c.gridwidth = 1;
makeButton("0", gridbag, c);
makeButton("=", gridbag, c);
makeButton(".", gridbag, c);
c.gridwidth = GridBagConstraints.REMAINDER;
makeButton("/", gridbag, c);
}
//创建标签为name的button,并使用约束对象c将按钮加入到gridbag布局
//的容器中
private void makeButton(String name,GridBagLayout
gridbag,GridBagConstraints c){
JButton button=new JButton(name);
gridbag.setConstraints(button,c);//将约束条件附加给按钮组件
add(button);//将按钮加入容器
}
public static void main(String[] args) {
// TODO Auto-generated method stub
GridBagLayoutDemo window=new GridBagLayoutDemo();
window.setTitle("GridBagLayout布局管理器");
window.pack();
window.setVisible(true);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// TODO Auto-generated method stu
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
------解决方案--------------------
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
在监听里判断,并进行计算就可以了;