提示:
数值字符串 转 int
String a = "3";
int b = Integer.parseInt(a);
System.out.println(b);
效果图如下:
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class work01 {
public static void main(String[] args) {
//构造器 创建一个最初不可见的新窗体
JFrame jf = new JFrame();
//设置窗体大小
jf.setSize(400, 300);
//设置窗体标志
jf.setTitle("我的计算器");
//设置窗体居中
jf.setLocationRelativeTo(null);
//设置窗体关闭时退出程序
//jf.setDefaultCloseOperation(3);
jf.setDefaultCloseOperation(3);
//设置窗体置顶
jf.setAlwaysOnTop(true);
//设置取消窗体的创建默认布局
jf.setLayout(null);
//文字
JLabel jl1 = new JLabel("=");
jl1.setBounds(290, 60, 100, 100);
jf.add(jl1);
//左框
JTextField jt1 = new JTextField();
jt1.setBounds(50, 85, 60, 50);
jt1.setBackground(Color.CYAN);
jf.add(jt1);
//中框
JTextField jt2 = new JTextField();
jt2.setBounds(210, 85, 60, 50);
jt2.setBackground(Color.CYAN);
jf.add(jt2);
//右框
JTextField jt3 = new JTextField();
jt3.setBounds(320, 85, 60, 50);
jt3.setBackground(Color.CYAN);
jf.add(jt3);
//按钮1
JButton jb1 = new JButton("+");
jb1.setBounds(130, 10, 60, 30);
jb1.setBackground(Color.GREEN);
ActionListener al1 = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
double jt11 = Integer.parseInt(jt1.getText());
double jt22 = Integer.parseInt(jt2.getText());
System.out.println(jt11);
System.out.println(jt22);
jt3.setText(String.valueOf((jt11 + jt22)));
}
};
jb1.addActionListener(al1);
jf.add(jb1);
JButton jb2 = new JButton("—");
jb2.setBounds(130, 60, 60, 30);
jb2.setBackground(Color.blue);
ActionListener al2 = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
double jt11 = Integer.parseInt(jt1.getText());
double jt22 = Integer.parseInt(jt2.getText());
jt3.setText(String.valueOf((jt11 - jt22)));
}
};
jb2.addActionListener(al2);
jf.add(jb2);
JButton jb3 = new JButton("X");
jb3.setBounds(130, 110, 60, 30);
jb3.setBackground(Color.orange);
ActionListener al3 = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
double jt11 = Integer.parseInt(jt1.getText());
double jt22 = Integer.parseInt(jt2.getText());
jt3.setText(String.valueOf((jt11 * jt22)));
}
};
jb3.addActionListener(al3);
jf.add(jb3);
JButton jb4 = new JButton("÷");
jb4.setBounds(130, 170, 60, 30);
jb4.setBackground(Color.BLUE);
ActionListener al4 = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
double jt11 = Integer.parseInt(jt1.getText());
double jt22 = Integer.parseInt(jt2.getText());
jt3.setText(String.valueOf((jt11 / jt22)));
}
};
jb4.addActionListener(al4);
jf.add(jb4);
//设置窗体可见
jf.setVisible(true);
}
}
运行结果如图: