网友您好, 请在下方输入框内输入要搜索的题目:
本题中定义了一个简单的计算器,可以进行基本的四则运算。程序中包含16个按钮用来表示0~9、+、-、 *、/、一运算符和小数点,程序顶部的文本框用来显示操作数以及结果。
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class java2{
public static void main(String[]args){
try{
UIManager.setLookAndFeel(UIManager.getSys-
temLookAndFeelClassName());
}
catch(Exception e){}
JFrame. frame=new CalculatorFrame();
frame.show();
}
}
class CalculatorPanel extends JPanel implements Ac-
tionListener{
private JTextField display;
private JButton btn;
private double arg=0;
private String p="=";
private boolean start=true;
public CalculatorPanel(){
setLayout(new BorderLayout());
display=new JTextField("0");
display.setEditable(false);
add(display,"North");
JPanel P=new JPanel();
P.setLayout(new GridLayout(4,4));
String buttons="789/456*123-0.=+":
for(int i=0;i<;buttons.length();i++){
btn=new JButton(buttons.substring(i,i+
1));
P.add(btn);
;
}
add(P,"Center");
}
public void actionPerformed(ActionEvent evt){
String s=evt.getActionCommand();
if(‘0 ‘<;=s.charAt(0)&&s.charAt(O)<;=‘
9‘‖ s.equals("-")){
if(start)display.setText(s):
else display.setText(display.getText()+s);
start=false;
}
else{
if(start){
if(s.equals("-")){
display.setText(s):
start=false;
}
else p=S;
}
else(
double x=
calculate(x);
op=S:
start=true;
}
}
}
public void calculate(double n){
if(op.equals("+"))arg+=n:
else if(op.equals("-"))arg-=n;
else if(op.equals("*"))arg*=n;
else if(op.equals("/"))arg/=n;
else if(op.equals("="))arg=n;
display.setText(""+arg);
}
}
class CalculatorFrame. extends JFrame{
public CalculatorFrame(){
setTitle("java2");
setSize(220,180);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
Container contentPane=getContentPane();
contentPane.add(new CalculatorPanel());
}
}
参考答案