Sorry, no corresponding articles.
--
--
--
no comments

スポンサーサイト

上記の広告は1ヶ月以上更新のないブログに表示されています。
新しい記事を書く事で広告が消せます。

Related Posts

Next and Prev

Comments + Add Comment

Leave a comment

02
03
2012
0 comments

Swingで電卓作り

Swingで電卓作り.jpg
今日の授業は、Swingで電卓を作りました。


Swing講座の中盤のメインである、
電卓のプログラミングでしたが、
参加した学生はたったの3人。。。


昨夜から始まった大寒波で、
通常授業でも普段の6割ぐらいの学生数、
明日が土曜で寒波が強まるとのことで、
放課後そのまま実家へ避難する学生が多かったからでした。


もともと、
全部説明しながら一緒に作る予定でしたが、
3人が全員プログラミングコンテストメンバーだったので、
画面の見た目やボタンアクションの呼び出し、
内部で扱う変数の準備まで一緒に作り、
その先の電卓としての演算や表示のロジックは
20分の時間を与えて考えてもらうことに。


普段、彼らがやっているアルゴリズムの学習の
活用を見てみるのが目的。


3人であーでもないこーでもないと話した後、
黙々と作ったり、デバッグしたり。


その結果、
1人電卓として機能させるところまで実装し、
残りの2人も8割ぐらいまで到達しました。


そのあとは、
自分が例として作った電卓の説明、
MVCモデルとその方法論で作った別バージョンの紹介をしました。


コード

授業版
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigDecimal;
import java.text.DecimalFormat;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class SwingCalculator extends JFrame {

/**
*
*/
private static final long serialVersionUID = 1L;

private JPanel contentPane = new JPanel();
private BorderLayout borderLayout1 = new BorderLayout();
private JTextField resultText = new JTextField();

private String strTemp = "";
private String strResult = "0";
private int operator = 0;

final static int KEYADD = 1;
final static int KEYSUB = 2;
final static int KEYMUL = 3;
final static int KEYDIV = 4;

public static void main(String args[]) {
SwingCalculator frame = new SwingCalculator("SwingCalculator");
frame.setVisible(true);
}

public SwingCalculator(String title) {
setTitle(title);
setSize(300, 250);
setLocationRelativeTo(null);
contentPane.setLayout(borderLayout1);
setContentPane(contentPane);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

resultText.setText("0");
resultText.setEditable(false);
resultText.setHorizontalAlignment(JTextField.RIGHT);
contentPane.add(resultText, BorderLayout.NORTH);

JPanel keyPanel = new JPanel();
keyPanel.setLayout(new GridLayout(5, 4));
keyPanel.add(new JButton(""), 0);
keyPanel.add(new JButton(""), 1);
keyPanel.add(new ClearButton("del"), 2);
keyPanel.add(new ClearButton("C"), 3);
keyPanel.add(new NumberButton("7"), 4);
keyPanel.add(new NumberButton("8"), 5);
keyPanel.add(new NumberButton("9"), 6);
keyPanel.add(new CalcButton("÷"), 7);
keyPanel.add(new NumberButton("4"), 8);
keyPanel.add(new NumberButton("5"), 9);
keyPanel.add(new NumberButton("6"), 10);
keyPanel.add(new CalcButton("×"), 11);
keyPanel.add(new NumberButton("1"), 12);
keyPanel.add(new NumberButton("2"), 13);
keyPanel.add(new NumberButton("3"), 14);
keyPanel.add(new CalcButton("-"), 15);
keyPanel.add(new NumberButton("0"), 16);
keyPanel.add(new NumberButton("."), 17);
keyPanel.add(new CalcButton("+"), 18);
keyPanel.add(new CalcButton("="), 19);
contentPane.add(keyPanel, BorderLayout.CENTER);
}

private String doCalc() {
BigDecimal bd1 = new BigDecimal(strResult);
BigDecimal bd2 = new BigDecimal(strTemp);
BigDecimal result = BigDecimal.ZERO;

switch(operator) {
case KEYADD:
result = bd1.add(bd2);
break;
case KEYSUB:
result = bd1.subtract(bd2);
break;
case KEYMUL:
result = bd1.multiply(bd2);
break;
case KEYDIV:
if(!bd2.equals(BigDecimal.ZERO)) {
result = bd1.divide(bd2, 12, 3);
} else {
JOptionPane.showMessageDialog(this, "error! (0 div)");
return strResult;
}
break;
}

if(result.toString().indexOf(".") >= 0) {
return result.toString().replaceAll("\\.0+$|0+$", "");
} else {
return result.toString();
}
}

private void showNumber(String strNum) {
DecimalFormat form = new DecimalFormat("#,##0");
String strDecimal = "";
String strInt = "";
String fText = "";

if(strNum.length() > 0) {
int decimalPoint = strNum.indexOf(".");

if(decimalPoint > -1) {
strDecimal = strNum.substring(decimalPoint);
strInt = strNum.substring(0, decimalPoint);
} else {
strInt = strNum;
}

fText = form.format(Double.parseDouble(strInt)) + strDecimal;
} else {
fText = "0";
}

resultText.setText(fText);
}

public class NumberButton extends JButton implements ActionListener {

private static final long serialVersionUID = 1L;

public NumberButton(String str) {
super(str);
this.addActionListener(this);
}

public void actionPerformed(ActionEvent evt) {
String keyNumber = this.getText();

if(keyNumber.equals(".")) {
if(strTemp.length() == 0) {
strTemp = "0.";
} else {
if(strTemp.indexOf(".") == -1) {
strTemp = strTemp + ".";
}
}
} else {
strTemp = strTemp + keyNumber;
}

showNumber(strTemp);
}
}

public class CalcButton extends JButton implements ActionListener {

private static final long serialVersionUID = 1L;

public CalcButton(String str) {
super(str);
this.addActionListener(this);
}

public void actionPerformed(ActionEvent e) {
if(operator != 0) {
if(strTemp.length() > 0) {
strResult = doCalc();
showNumber(strResult);
}
} else {
if(strTemp.length() > 0) {
strResult = strTemp;
}
}

strTemp = "";

if(this.getText().equals("+")) {
operator = KEYADD;
} else if(this.getText().equals("-")) {
operator = KEYSUB;
} else if(this.getText().equals("×")) {
operator = KEYMUL;
} else if(this.getText().equals("÷")) {
operator = KEYDIV;
} else {
operator = 0;
}
}

}

public class ClearButton extends JButton implements ActionListener {

private static final long serialVersionUID = 1L;

public ClearButton(String str) {
super(str);
this.addActionListener(this);
}

public void actionPerformed(ActionEvent evt) {
if(this.getText().equals("C")) {
strTemp = "";
strResult = "0";
operator = 0;
resultText.setText("0");
} else if(this.getText().equals("del")) {
if(strTemp.length() == 0) {
return;
} else {
strTemp = strTemp.substring(0, strTemp.length() - 1);
}
showNumber(strTemp);
}
}

}

}
MVC版
public class SwingCalculatorMVC {

@SuppressWarnings("unused")
public static void main(String args[]) {
SwingCalculatorMVCModel model = new SwingCalculatorMVCModel();
SwingCalculatorMVCView view = new SwingCalculatorMVCView();
SwingCalculatorMVCController controller = new SwingCalculatorMVCController(model, view);
view.setVisible(true);
}

}


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class SwingCalculatorMVCController {

//... The Controller needs to interact with both the Model and View.
private SwingCalculatorMVCModel model;
private SwingCalculatorMVCView view;

public SwingCalculatorMVCController(SwingCalculatorMVCModel m, SwingCalculatorMVCView v) {
model = m;
view = v;
view.addNumberListener(new NumberListener());
view.addCalcListener(new CalcListener());
view.addClearListener(new ClearListener());
}

class NumberListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String number = "";
number = e.getActionCommand();

if(number.equals(".")) {
if(model.getStrTemp().length() == 0) {
model.setStrTemp("0.");
} else {
if(model.getStrTemp().indexOf(".") == -1) {
model.setStrTemp(model.getStrTemp() + ".");
}
}
} else {
model.setStrTemp(model.getStrTemp() + number);
}

view.setResultText(model.getStrTemp());
}
}


class CalcListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
if(model.getOperator() != 0) {
if(model.getStrTemp().length() > 0) {
model.setStrResult(model.doCalc());
view.setResultText(model.getStrResult());
}
} else {
if(model.getStrTemp().length() > 0) {
model.setStrResult(model.getStrTemp());
}
}

model.setStrTemp("");

if(e.getActionCommand().equals("+")) {
model.setOperator(SwingCalculatorMVCModel.KEYADD);
} else if(e.getActionCommand().equals("-")) {
model.setOperator(SwingCalculatorMVCModel.KEYSUB);
} else if(e.getActionCommand().equals("×")) {
model.setOperator(SwingCalculatorMVCModel.KEYMUL);
} else if(e.getActionCommand().equals("÷")) {
model.setOperator(SwingCalculatorMVCModel.KEYDIV);
} else {
model.setOperator(0);
}
} catch(SwingCalculatorMVCException ex) {
view.showError(ex.getMessage());
model.reset();
view.reset();
}
}
}

class ClearListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("C")) {
model.reset();
view.reset();
} else if(e.getActionCommand().equals("del")) {
if(model.getStrTemp().length() == 0) {
return;
} else {
model.setStrTemp(model.getStrTemp().substring(0, model.getStrTemp().length() - 1));
}
view.setResultText(model.getStrTemp());
}
}
}

}


public class SwingCalculatorMVCException extends Exception {

/**
*
*/
private static final long serialVersionUID = 1L;

public SwingCalculatorMVCException(String message) {
super(message);
}

}


import java.math.BigDecimal;

public class SwingCalculatorMVCModel {

// constants
public static final int KEYADD = 1;
public static final int KEYSUB = 2;
public static final int KEYMUL = 3;
public static final int KEYDIV = 4;

// variable members
private String strResult;
private String strTemp;
private int operator;

//========== constructor ==========//
SwingCalculatorMVCModel() {
reset();
}

//========== method ==========//
public void reset() {
strResult = "0";
strTemp = "";
operator = 0;
}

public String getStrTemp() {
return strTemp;
}

public void setStrTemp(String str) {
this.strTemp = str;
}

public String getStrResult() {
return strResult;
}

public void setStrResult(String str) {
this.strResult = str;
}

public int getOperator() {
return operator;
}

public void setOperator(int ope) {
this.operator = ope;
}

public String doCalc() throws SwingCalculatorMVCException {
BigDecimal bd1 = new BigDecimal(strResult);
BigDecimal bd2 = new BigDecimal(strTemp);
BigDecimal result = BigDecimal.ZERO;

switch(operator) {
case KEYADD:
result = bd1.add(bd2);
break;
case KEYSUB:
result = bd1.subtract(bd2);
break;
case KEYMUL:
result = bd1.multiply(bd2);
break;
case KEYDIV:
if(!bd2.equals(BigDecimal.ZERO)) {
result = bd1.divide(bd2, 12, 3);
} else {
SwingCalculatorMVCException e = new SwingCalculatorMVCException("error! (0 div)");
throw e;
}

break;
}

if(result.toString().indexOf(".") >= 0) {
return result.toString().replaceAll("\\.0+$|0+$", "");
} else {
return result.toString();
}
}

}


import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.text.DecimalFormat;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

public class SwingCalculatorMVCView extends JFrame {

/**
*
*/
private static final long serialVersionUID = 1L;

//... Constants
private static final String INITIAL_VALUE = "0";

// components
private JPanel contentPane = new JPanel();
private BorderLayout borderLayout1 = new BorderLayout();
private JTextField resultText = new JTextField();
private JPanel keyPanel = new JPanel();
private JButton button0 = new JButton("0");
private JButton button1 = new JButton("1");
private JButton button2 = new JButton("2");
private JButton button3 = new JButton("3");
private JButton button4 = new JButton("4");
private JButton button5 = new JButton("5");
private JButton button6 = new JButton("6");
private JButton button7 = new JButton("7");
private JButton button8 = new JButton("8");
private JButton button9 = new JButton("9");
private JButton buttonEqu = new JButton("=");
private JButton buttonAdd = new JButton("+");
private JButton buttonSub = new JButton("-");
private JButton buttonMul = new JButton("×");
private JButton buttonDiv = new JButton("÷");
private JButton buttonDel = new JButton("del");
private JButton buttonClr = new JButton("C");
private JButton buttonPoi = new JButton(".");
private JButton button10 = new JButton("");
private JButton button11 = new JButton("");

//========== constructor ==========//
SwingCalculatorMVCView() {
reset();
resultText.setEditable(false);
resultText.setHorizontalAlignment(JTextField.RIGHT);

contentPane.setLayout(borderLayout1);

keyPanel.setLayout(new GridLayout(5, 4));
keyPanel.add(button10, 0);
keyPanel.add(button11, 1);
keyPanel.add(buttonDel, 2);
keyPanel.add(buttonClr, 3);
keyPanel.add(button7, 4);
keyPanel.add(button8, 5);
keyPanel.add(button9, 6);
keyPanel.add(buttonDiv, 7);
keyPanel.add(button4, 8);
keyPanel.add(button5, 9);
keyPanel.add(button6, 10);
keyPanel.add(buttonMul, 11);
keyPanel.add(button1, 12);
keyPanel.add(button2, 13);
keyPanel.add(button3, 14);
keyPanel.add(buttonSub, 15);
keyPanel.add(button0, 16);
keyPanel.add(buttonPoi, 17);
keyPanel.add(buttonAdd, 18);
keyPanel.add(buttonEqu, 19);

contentPane.add(resultText, BorderLayout.NORTH);
contentPane.add(keyPanel, BorderLayout.CENTER);

this.setTitle("SwingCalculator - MVC");
this.setSize(300, 250);
this.setLocationRelativeTo(null);
this.setContentPane(contentPane);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

//========== method ==========//
void reset() {
resultText.setText(INITIAL_VALUE);
}

void showError(String errMessage) {
JOptionPane.showMessageDialog(this, errMessage);
}

void setResultText(String text) {
resultText.setText(commaNumber(text));
}

private String commaNumber(String strNum) {
DecimalFormat form = new DecimalFormat("#,##0");
String strDecimal = "";
String strInt = "";
String fText = "";

if(strNum.length() > 0) {
int decimalPoint = strNum.indexOf(".");

if(decimalPoint > -1) {
strDecimal = strNum.substring(decimalPoint);
strInt = strNum.substring(0, decimalPoint);
} else {
strInt = strNum;
}

fText = form.format(Double.parseDouble(strInt)) + strDecimal;
} else {
fText = "0";
}

return fText;
}

void addNumberListener(ActionListener num) {
button0.addActionListener(num);
button1.addActionListener(num);
button2.addActionListener(num);
button3.addActionListener(num);
button4.addActionListener(num);
button5.addActionListener(num);
button6.addActionListener(num);
button7.addActionListener(num);
button8.addActionListener(num);
button9.addActionListener(num);
buttonPoi.addActionListener(num);
}

void addCalcListener(ActionListener cal) {
buttonEqu.addActionListener(cal);
buttonAdd.addActionListener(cal);
buttonSub.addActionListener(cal);
buttonMul.addActionListener(cal);
buttonDiv.addActionListener(cal);
}

void addClearListener(ActionListener clr) {
buttonClr.addActionListener(clr);
buttonDel.addActionListener(clr);
}

}

Comments + Add Comment

Leave a comment

Urgench Time

Urgench Temp

Click for Urgench, Uzbekistan Forecast

Tweets

Counter (visitor)

上記広告は1ヶ月以上更新のないブログに表示されています。新しい記事を書くことで広告を消せます。