java仿win7计算器布局
代码:
package calculator; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class cal extends JFrame{ private JTextField tf =new JTextField("0"); public void addButton(String name,GridBagLayout g ,GridBagConstraints c){ JButton btn = new JButton(name); g.setConstraints(btn, c); add(btn); } public void lauch(){ //文本是不可以编辑的 tf.setEditable(false); GridBagLayout gb = new GridBagLayout(); setLayout(gb); GridBagConstraints c = new GridBagConstraints(); //文本是放在最上面的,占用那一行所有的空间 c.weightx=0.3; c.weighty=0.3; c.gridy = 0 ; // c.anchor = GridBagConstraints.EAST; c.gridwidth = 4 ; c.fill = GridBagConstraints.BOTH; add(tf,c); //需要另起一行添加按钮 c.gridy =1; c.gridwidth =1 ; addButton("MC", gb, c); addButton("M+", gb, c); addButton("M-", gb, c); addButton("MR", gb, c); c.gridy = 2; addButton("c", gb, c); addButton("+", gb, c); addButton("/", gb, c); addButton("*", gb, c); c.gridy = 3; addButton("7", gb, c); addButton("8", gb, c); addButton("9", gb, c); addButton("-", gb, c); c.gridy = 4; addButton("4", gb, c); addButton("5", gb, c); addButton("6", gb, c); addButton("+", gb, c); c.gridy = 5 ; addButton("1", gb, c); addButton("2", gb, c); addButton("3", gb, c); c.gridx = GridBagConstraints.RELATIVE; c.gridheight= GridBagConstraints.REMAINDER ; c.fill = GridBagConstraints.BOTH; //c.anchor = GridBagConstraints.SOUTH; addButton("=", gb, c); c.gridy = 6 ; c.gridx= 0 ; c.gridheight = 1 ; c.gridwidth =2 ; addButton("0",gb,c); c.gridx = GridBagConstraints.RELATIVE; c.gridwidth =1 ; addButton(".",gb,c); setBounds(100,100,300,500); //this.pack(); setVisible(true); } public static void main(String[] args) { cal c = new cal(); c.lauch(); } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。