赞
踩
MyFrame.java
private void btnCalActionPerformed(ActionEvent e) { // TODO add your code here // 获取第一个操作数 String firstNumStr = this.firstNum.getText().trim(); // 获取第二个操作数 String secondNumStr = this.secondNum.getText().trim(); // 获取操作符 String selectOperatorStr = this.selectedOperator.getSelectedItem().toString(); // System.out.println("第一个操作数: " + firstNumStr); // System.out.println("第二个操作数: " + secondNumStr); // System.out.println("操作符: " + selectOperatorStr); int firstNum = Integer.parseInt(firstNumStr); int secondNum = Integer.parseInt(secondNumStr); int res = 0; switch (selectOperatorStr) { case "+": res = firstNum + secondNum; break; case "-": res = firstNum - secondNum; break; case "*": res = firstNum * secondNum; break; case "/": res = firstNum / secondNum; break; default: break; } this.resNum.setText(String.valueOf(res)); }
public class Main {
public static void main(String[] args) {
MyFrame f = new MyFrame();
f.setVisible(true);
}
}
UIUtils.java
package swingtest; import javax.swing.*; import java.awt.*; public class UIUtils { public UIUtils() { } // 修改窗体的图标 public static void setFrameImage(JFrame jf) { // 获取工具类对象 Toolkit tk = Toolkit.getDefaultToolkit(); // 获取图片 Image image = tk.getImage("src\\swingtest\\resource\\jsq.jpg"); // 给窗体设置 jf.setIconImage(image); } }
MyFrame.java
UIUtils.java
// 设置窗体居中 public static void setFrameCenter(JFrame jf) { /* * 1.获取屏幕的长、宽 * 2、获取窗体的长、宽 * 3、(屏幕的长-窗体的长)/ 2; (屏幕的宽-窗体的宽) / 2; 作为新坐标 * * */ // 获取工具对象 Toolkit tk = Toolkit.getDefaultToolkit(); // 获取屏幕的宽、高 Dimension d = tk.getScreenSize(); double screenWidth = d.getWidth(); double screenHeight = d.getHeight(); // 获取窗体的宽、高 int frameWidth = jf.getWidth(); int frameHeight = jf.getHeight(); int width = (int) (screenWidth - frameWidth) / 2; int height = (int) (screenHeight - frameHeight) / 2; // 设置窗体的坐标 jf.setLocation(width, height); }
MyFrame.java
MyFrame.java
private void btnCalActionPerformed(ActionEvent e) { // TODO add your code here // 获取第一个操作数 String firstNumStr = this.firstNum.getText().trim(); // 获取第二个操作数 String secondNumStr = this.secondNum.getText().trim(); // 获取操作符 String selectOperatorStr = this.selectedOperator.getSelectedItem().toString(); // System.out.println("第一个操作数: " + firstNumStr); // System.out.println("第二个操作数: " + secondNumStr); // System.out.println("操作符: " + selectOperatorStr); // 数据校验,必须是数字字符串 String regex = "\\d+"; if (!(firstNumStr.matches(regex))) { JOptionPane.showMessageDialog(this, "第一个操作数有误"); this.firstNum.setText(""); this.firstNum.requestFocus(); return; } int firstNum = Integer.parseInt(firstNumStr); int secondNum = Integer.parseInt(secondNumStr); int res = 0; switch (selectOperatorStr) { case "+": res = firstNum + secondNum; break; case "-": res = firstNum - secondNum; break; case "*": res = firstNum * secondNum; break; case "/": res = firstNum / secondNum; break; default: break; } this.resNum.setText(String.valueOf(res)); }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。