乗算タスクを実行するアクションリスナーを作成しようとしています。しかし、それは入力された最後の数字を無視するようです。最後のコマンドを追跡するために2番目の変数が必要であると思っているので、等価ボタンを押すと、現在の数字が前のコマンドに追加されます。しかし、私はイコールボタンが押されていればタスクを実行する必要はありませんか?Java ActionListener
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String numbers = e.getActionCommand();
if (begin) {
textField.setText(numbers);
begin = false;
}
else if (numbers.equals("C")) {
textField.setText("0.0");
action.reset();
}
else
textField.setText(textField.getText() + numbers);
}
}
class OperatorListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String command = e.getActionCommand();
String text = textField.getText();
if (begin) {
textField.setText("0.0");
action.setTotal("0.0");
}
else {
if (command.equals("+")) {
action.add(text);
begin = true;
}
else if (command.equals("=")) {
textField.setText(text);
System.out.println(action.getTotal());
}
textField.setText(action.getTotal());
}
}
}
変数の説明。 begin
は、単にJTextField
の現在の状態が空白であるかどうかをチェックします。 action
は、単純に "追加"する方法です、私はそれが欲しい他の呼び出しがあります。
最後の数字を無視しないように、最後のコマンドを追跡したり回避する方法に関する提案はありますか?これらのタスクは電卓のタスクに似ています。
EDIT:興味のある方のために 、ここで私がなってしまったものです。
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String numbers = e.getActionCommand();
// check if a number has been pressed
if (begin) {
textField.setText(numbers);
begin = false;
}
// if clear is checked
else if (numbers.equals("C")) {
action.reset();
begin = true;
operator = "=";
textField.setText("0.0");
}
// Once a number is pressed keep adding it to the text field until an operator is pressed
else
textField.setText(textField.getText() + numbers);
}
}
/**
* Action listener for Operators
*/
class OperatorListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
// String command = e.getActionCommand();
// if nothing has been pressed
if (begin) {
textField.setText("0.0");
begin = false;
// else begin performing operation pressed
} else {
begin = true;
String text = textField.getText();
// right away add the value of the text field
if (operator.equals("=")) {
action.setTotal(text);
}
else if (operator.equals("+")) {
action.add(text);
}
// and so on for all the other operators.
textField.setText("" + action.getTotal());
// now capture the operator pressed.
operator = e.getActionCommand();
}
}
}
for NumberインスタンスのみJFormattedTextField http://download.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.htmlここに示す – mKorbel
「ActionListener」はSwingではなくAWTです。 –
@Andrew:ActionListenerはAWTパッケージに含まれていますが、JButtonにはActionListenerをパラメータとするaddActionListener functinoがあります。したがって、Javaの発明者はSwingプログラムで使用することを期待しているようです。これは私がほとんど常にボタンのクリックを処理する方法です(私はSwingプログラムを書いたときに戻っています)。別の方法がありますか? – Jay