Swingで計算機

snsのコミュで課題が丸投げされていたので、まずはボタンだけ。
計算機自体を実装するかは不明ですがw


↑実行結果(Windows7 Professional 64bit)

http://www.is.titech.ac.jp/~kawachi/class/2009/cs1/ex12/img/fig1.png
↑参考

package ex12;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;

import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * 計算機。
 * @see <a href="http://mixi.jp/view_bbs.pl?id=49697103&comment_count=0&comm_id=1017129">mixi:Javaの課題丸投げ トピック/関数電卓の作成</a>
 * @see <a href="http://mixi.jp/show_friend.pl?id=4677909">mixi:ヤムチャさん</a>
 * @see <a href="http://www.is.titech.ac.jp/~kawachi/class/2009/cs1/ex12/assignment12.html">計算機科学第一 演習(後半) 第十二回課題</a>
 * 
 */
public class MyCalc extends JFrame {
  private static final long serialVersionUID = 1L;
  public MyCalc() {
    super("計算機");
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }

  GridBagLayout _gbl = new GridBagLayout();
  GridBagConstraints _gbc = new GridBagConstraints();

  void addButton(JComponent parent, JComponent c, int x, int y, int w, int h) {
    _gbc.fill = GridBagConstraints.BOTH;
    _gbc.gridx = x;
    _gbc.gridy = y;
    _gbc.gridwidth = w;
    _gbc.gridheight = h;
    _gbl.setConstraints(c, _gbc);
    parent.add(c);
  }
  JPanel keys() {
    JPanel pane = new JPanel(_gbl);
    int x = 0;
    int y = 0;
    addButton(pane, new JButton("MC"), x++, y, 1, 1);
    addButton(pane, new JButton("M+"), x++, y, 1, 1);
    addButton(pane, new JButton("M-"), x++, y, 1, 1);
    addButton(pane, new JButton("MR"), x++, y, 1, 1);
    x = 0; y++;
    addButton(pane, new JButton("C"), x++, y, 1, 1);
    addButton(pane, new JButton("±"), x++, y, 1, 1);
    addButton(pane, new JButton("÷"), x++, y, 1, 1);
    addButton(pane, new JButton("×"), x++, y, 1, 1);
    x = 0; y++;
    addButton(pane, new JButton("7"), x++, y, 1, 1);
    addButton(pane, new JButton("8"), x++, y, 1, 1);
    addButton(pane, new JButton("9"), x++, y, 1, 1);
    addButton(pane, new JButton("-"), x++, y, 1, 1);
    x = 0; y++;
    addButton(pane, new JButton("4"), x++, y, 1, 1);
    addButton(pane, new JButton("5"), x++, y, 1, 1);
    addButton(pane, new JButton("6"), x++, y, 1, 1);
    addButton(pane, new JButton("+"), x++, y, 1, 1);
    x = 0; y++;
    addButton(pane, new JButton("1"), x++, y, 1, 1);
    addButton(pane, new JButton("2"), x++, y, 1, 1);
    addButton(pane, new JButton("3"), x++, y, 1, 1);
    addButton(pane, new JButton("="), x++, y, 1, 2);
    x = 0; y++;
    addButton(pane, new JButton("0"), x++, y, 2, 1); x++;
    addButton(pane, new JButton("."), x++, y, 1, 1);
    return pane;
  }
  private void run() {
    JPanel pane = keys();
//    pane.setBorder(BorderFactory.createEmptyBorder(30, 30, 10, 30));
    getContentPane().add(pane);
    pack();
    setVisible(true);
  }

  public static void main(String[] args) {
    new MyCalc().run();
  }
}