📄 counter.java
字号:
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.util.EventListener;
import java.awt.event.ActionEvent;
public class Counter extends JFrame implements ActionListener
{
JLabel lb1,lb2,lb3,lb4,lb5,lb6;
JTextField tf=new JTextField("");
JButton bt1[]=new JButton[10];
JButton clear,equl;
JButton jia,jian,cheng,chu;
String s;
float i=0,result=0;
boolean flag=true;
JPanel jp1,jp2,jp3,jp4,jp5,jp6;
public Counter()
{
super("迷你计算器");
Container con=this.getContentPane();
con.setLayout(new BorderLayout());
lb1=new JLabel(" 计算结果:");
lb2=new JLabel(" ");
lb3=new JLabel(" ");
lb4=new JLabel(" ");
lb5=new JLabel(" ");
lb6=new JLabel(" ");
tf=new JTextField("0");
for(int i=0;i<10;i++)
{
bt1[i]=new JButton(""+i);
}
clear=new JButton("归零");
equl=new JButton("=");
jia=new JButton("+");
jian=new JButton("-");
cheng=new JButton("*");
chu=new JButton("/");
jp1=new JPanel();
jp1.setLayout(new GridLayout(1,2));
jp2=new JPanel();
jp2.setLayout(new GridLayout(4,3));
jp3=new JPanel();
jp3.setLayout(new BorderLayout());
jp4=new JPanel();
jp4.setLayout(new GridLayout(4,1));
jp5=new JPanel();
jp5.setLayout(new BorderLayout());
jp6=new JPanel();
jp6.setLayout(new BorderLayout());
con.add("North",jp1);
jp1.add(lb1);
jp1.add(tf);
con.add("Center",jp5);
jp5.add("Center",jp3);
jp5.add("East",lb3);
jp5.add("West",lb4);
jp5.add("South",lb5);
jp3.add("North",lb2);
jp3.add("West",jp6);
jp6.add("East",lb6);
jp6.add("West",jp2);
for(int i=0;i<10;i++)
{
jp2.add(bt1[i]);
bt1[i].addActionListener(this);
}
jp2.add(clear);
clear.addActionListener(this);
jp2.add(equl);
equl.addActionListener(this);
jp3.add("East",jp4);
jp4.add(jia);
jia.addActionListener(this);
jp4.add(jian);
jian.addActionListener(this);
jp4.add(cheng);
cheng.addActionListener(this);
jp4.add(chu);
chu.addActionListener(this);
this.setSize(300,300);
this.setVisible(true);
}
public static void main(String args[])
{
new Counter();
}
public void actionPerformed(ActionEvent e)
{
// TODO: Add your code here
for(int j=0;j<10;j++)
{
if(e.getSource()==bt1[j])
{
if(i==0)
tf.setText(""+j);
else
{
tf.setText(tf.getText()+j);
}
i=Float.parseFloat(tf.getText());
}
}
if(e.getSource()==clear)
{
tf.setText("0");
result=0;
i=Float.parseFloat(tf.getText());
}
if(e.getSource()==equl)
{
if(s=="+") result=result+i;
if(s=="-") result=result-i;
if(s=="*") result=result*i;
if(s=="/"&&i!=0) result=result/i;
else if(s!="+"&&s!="-"&&s!="*")
flag=false;
if(flag==false)
{
tf.setText("除数不能为
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -