第二个题目代码:
------------------------------------------------
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class Minicalc{
public static void main(String[] args){
JFrame frame=new JFrame("简易计算器");
Container pane=frame.getContentPane();
JTextField firstnumber=new JTextField(10);
JTextField secondnumber=new JTextField(10);
JTextField result=new JTextField(10);
JButton addButton=new JButton("+");
JButton subButton=new JButton("-");
JButton mulButton=new JButton("*");
JButton divButton=new JButton("/");
pane.setLayout(new GridLayout(5,2));
pane.add(new JLabel("Enter a number"));
pane.add(firstnumber);
pane.add(new JLabel("Enter a number"));
pane.add(secondnumber);
pane.add(new JLabel("Result"));
pane.add(result);
pane.add(addButton);
pane.add(subButton);
pane.add(mulButton);
pane.add(divButton);
DoMath listener=new DoMath(firstnumber,secondnumber,result);
addButton.addActionListener(listener);
subButton.addActionListener(listener);
mulButton.addActionListener(listener);
divButton.addActionListener(listener);
frame.pack();
frame.show();
}
}
class DoMath implements ActionListener{
private JTextField inputone,inputtwo,output;
char F[]=(e.getActionCommand())toCharArray();
DoMath(JTextField first,JTextField second,JTextField result){
inputone=first;
inputtwo=second;
output=result;
}
public void actionPerformed(ActionEvent e){
double first,second;
first=Double.parseDouble(inputone.getText().trim());
second=Double.parseDouble(inputtwo.getText().trim());
switch(F){
case '+' : output.setText(String.valueOf(first+second));break;
case '-' : output.setText(String.valueOf(first-second));break;
case '*' : output.setText(String.valueOf(first*second));break;
case '/' : output.setText(String.valueOf(first/second));break;
}
/*if (e.getActionCommand().equals("+"))
output.setText(String.valueOf(first+second));
else { if (e.getActionCommand().equals("-"))
output.setText(String.valueOf(first-second));
else {if (e.getActionCommand().equals("*"))
output.setText(String.valueOf(first*second)) ;
else
output.setText(String.valueOf(first/second));
}
}*/
}
}