简单的加减乘除(+-*/ ) 计算器 下拉框 按钮事件
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
public class BaseFrame extends JFrame{
public BaseFrame (String title)
{
setLayout(null);
setTitle(title);
setSize(800,300);
this.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});//关闭窗口的匿名类
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
}
public void showMe(){
setVisible(true);
}
}
import java.awt.GridLayout;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;
public class Calc {
public static void main(String[] args) {
JPanel j=new JPanel();
BaseFrame f=new BaseFrame("hello");
j.setSize(800,50);
j.setLayout(new GridLayout(1,5,5,55));
final JTextField t1=new JTextField();
final JTextField t2=new JTextField();
final JTextField t3=new JTextField();
final JComboBox cb=new JComboBox();
cb.addItem("+");
cb.addItem("-");
cb.addItem("*");
cb.addItem("/");
JButton btn =new JButton("=");
j.add(t1);
j.add(cb);
j.add(t2);
j.add(btn);
j.add(t3);
j.setVisible(true);
f.add(j);
f.showMe();
// final String s = cb.getSelectedItem().toString(); 说明 不能首先或、获得cb 的值因为 代码的执行从上到下 永远只能获取 到第一个item “+” 而 后面的事件记录无法实现
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(cb.getSelectedItem().toString().equals("+")){
int c=0;
int num1 = Integer.parseInt(t1.getText());
int num2 = Integer.parseInt(t2.getText());
c=num1+num2;
String s1=Integer.toString(c);
t3.setText(s1);
}
else if(cb.getSelectedItem().toString().equals("-")){
int c=0;
int num1 = Integer.parseInt(t1.getText());
int num2 = Integer.parseInt(t2.getText());
c=num1-num2;
String s1=Integer.toString(c);
t3.setText(s1);
}
else if(cb.getSelectedItem().toString().equals("*")){
int c=0;
int num1 = Integer.parseInt(t1.getText());
int num2 = Integer.parseInt(t2.getText());
c=num1*num2;
String s1=Integer.toString(c);
t3.setText(s1);
}
else if(cb.getSelectedItem().toString().equals("/")){
int c=0;
int num1 = Integer.parseInt(t1.getText());
int num2 = Integer.parseInt(t2.getText());
c=num1/num2;
String s1=Integer.toString(c);
t3.setText(s1);
}
else {
System.out.print("No");
}
}
});
}
}
🐳 作者:hiszm 📢 版权:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,万分感谢。 💬 留言:同时 , 如果文中有什么错误,欢迎指出。以免更多的人被误导。 |
![]() |