模拟四则运算案例
NewJFrame.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package cn.ch.view;
import cn.ch.util.UiUtil;
import cn.ch.util.MyLookAndFeel;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
/**
*
* @author PC
*/
public class NewJFrame extends javax.swing.JFrame {
/**
* Creates new form NewJFrame
*/
public NewJFrame() {
initComponents();
init();
}
private void init() {
this.setTitle("模拟四则运算");
UiUtil.setFrameIcon(this);
UiUtil.setFrameCenter(this);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
resultNumber = new javax.swing.JTextField();
firstNumber = new javax.swing.JTextField();
secondNumber = new javax.swing.JTextField();
selectOperator = new javax.swing.JComboBox();
jLabel4 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("第一个操作数");
jLabel2.setText("第二个操作数");
jLabel3.setText("结果");
resultNumber.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
resultNumberActionPerformed(evt);
}
});
firstNumber.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
firstNumberActionPerformed(evt);
}
});
secondNumber.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
secondNumberActionPerformed(evt);
}
});
selectOperator.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "+", "-", "*", "/" }));
selectOperator.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
selectOperatorActionPerformed(evt);
}
});
jLabel4.setText("=");
jButton1.setText("计算");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(65, 65, 65)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(firstNumber))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(selectOperator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(14, 14, 14)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(secondNumber))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 8, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel3)
.addComponent(resultNumber)
.addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 90, Short.MAX_VALUE))
.addContainerGap(57, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(32, 32, 32)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(jLabel2)
.addComponent(jLabel3))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(resultNumber, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(firstNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(selectOperator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(secondNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4)))
.addGap(18, 18, 18)
.addComponent(jButton1)
.addContainerGap(21, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
//获取第一个操作数
String firstNumberString = this.firstNumber.getText().trim();
//获取运算符
String selectOperator = this.selectOperator.getSelectedItem().toString();
//获取第二个操作数
String secondNumberString = this.secondNumber.getText().trim();
String regex="\\d+";
if(!firstNumberString.matches(regex)){
JOptionPane.showMessageDialog(this, "第一个操作数不满足要求必须是数字");
this.firstNumber.setText(null);
this.firstNumber.requestFocus();
return;
}
if(!secondNumberString.matches(regex)){
JOptionPane.showMessageDialog(this, "第二个操作数不满足要求必须是数字");
this.secondNumber.setText(null);
this.secondNumber.requestFocus();
return;
}
//将字符串转换为数字
int firstNumber = Integer.parseInt(firstNumberString);
int secondNumber = Integer.parseInt(secondNumberString);
//定义变量接收结果
int resultNumber=0;
switch (selectOperator) {
case "+":
resultNumber=firstNumber+secondNumber;
break;
case "-":
resultNumber=firstNumber-secondNumber;
break;
case "*":
resultNumber=firstNumber*secondNumber;
break;
case "/":
resultNumber=firstNumber/secondNumber;
break;
}
//把结果赋值给结果框
this.resultNumber.setText(String.valueOf(resultNumber));
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
try {
//</editor-fold>
UIManager.setLookAndFeel(MyLookAndFeel.JTATTOO_BERNSTEIN);
} catch (ClassNotFoundException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (UnsupportedLookAndFeelException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextField firstNumber;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JTextField resultNumber;
private javax.swing.JTextField secondNumber;
private javax.swing.JComboBox selectOperator;
// End of variables declaration
}
如何设置窗体居中和修改窗体的图标
UiUtil.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package cn.ch.util;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.JFrame;
/**
*专门做界面效果的类
* @author PC
*/
public class UiUtil {
private UiUtil(){
}
//修改窗体的图标
public static void setFrameIcon(JFrame jf){
//获取工具类对象
//public static Toolkit getDefaultToolkit();获取默认工具包
Toolkit tk=Toolkit.getDefaultToolkit();
//根据路径获取图片(相对路径)
Image i=tk.getImage("src/cn/ch/resource/jjcc.jpg");
//给窗体设置图片
jf.setIconImage(i);
}
//设置窗体居中
public static void setFrameCenter(JFrame jf){
/*
思路:
A:获取屏幕的宽和高
B:获取窗体的宽和高
C:(用屏幕的宽-窗体的宽)/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);
}
}
对四则运算案例加入校验和提示
String regex="\\d+";
if(!firstNumberString.matches(regex)){
JOptionPane.showMessageDialog(this, "第一个操作数不满足要求必须是数字");
this.firstNumber.setText(null);
this.firstNumber.requestFocus();
return;
}
if(!secondNumberString.matches(regex)){
JOptionPane.showMessageDialog(this, "第二个操作数不满足要求必须是数字");
this.secondNumber.setText(null);
this.secondNumber.requestFocus();
return;
}