火之神神乐--圆舞 ------ Java期末作业
在计算机专业学子的期末之际,往往是各种各样的期末课设来临之时。Java也在其中,而计算器算是Java课设中最简单的一个,所以废话不多说,直接上代码!
本题采用的 是MVC常见的架构模式
1.首先是swing窗口的制作(窗口制作不太美观 ,勉强能用🙂,各位可以自己修改)
package Swing.calculator;
import javax.swing.*;
import javax.swing.border.MatteBorder;
import java.awt.*;
import java.awt.event.ActionListener;
public class CalculatorWindow extends JFrame{
public JTextField text1;
public JTextField text2;
public JTextField text3;
public JTextField text4;
public JTextArea text5;
JButton [][]buttons=new JButton[4][5];
public JButton jButton1;
public JButton jButton2;
public JButton jButton3;
public CalculatorWindow(){
//左边面板
final BorderLayout borderLayout1=new BorderLayout();
final JPanel left=new JPanel();
left.setLayout(borderLayout1);
//1.左上面板
final JPanel leftTop=new JPanel();
final FlowLayout flowLayout=new FlowLayout();
flowLayout.setHgap(5);
leftTop.setLayout(flowLayout);
//边框样式设计
MatteBorder border1=new MatteBorder(1,1,1,1,new Color(220, 50, 50));
text1=new JTextField(15);
text2=new JTextField(5);
text3=new JTextField(15);
text1.setBorder(border1);
text2.setBorder(border1);
text3.setBorder(border1);
text1.setSize(100,30);
text2.setSize(50,30);
text3.setSize(100,30);
leftTop.add(text1);
leftTop.add(text2);
leftTop.add(text3);
left.add(leftTop,BorderLayout.NORTH);
//左中面板
final JPanel leftCenter=new JPanel();
final GridLayout gridLayout=new GridLayout(4,5);
gridLayout.setHgap(5);
gridLayout.setVgap(5);
leftCenter.setLayout(gridLayout);
String [][]names={{"1","2","3","/","c"},{"4","5","6","*","退格"},{"7","8","9","-","sqrt"},{"0","+/-",".","+","="}};
Font font=new Font("宋体",Font.BOLD,20);
for(int row=0;row<4;row++)
{
for(int col=0;col<5;col++){
buttons[row][col]=new JButton(names[row][col]);
buttons[row][col].setPreferredSize(new Dimension(20,20));
buttons[row][col].setBorderPainted(false);//边框去掉
buttons[row][col].setBackground(Color.lightGray);
buttons[row][col].setFont(font);
leftCenter.add(buttons[row][col]);
}
}
left.add(leftCenter,BorderLayout.CENTER);
//右边面板
BorderLayout borderLayout2=new BorderLayout();
final JPanel right=new JPanel();
right.setLayout(borderLayout2);
//右上面板
final JPanel rightTop=new JPanel();
text4=new JTextField(20);
text4.setSize(60,40);
text4.setForeground(Color.red);
//边框样式设置
MatteBorder border=new MatteBorder(1,1,1,1,new Color(97, 139, 255));
text4.setBorder(border);
rightTop.add(text4);
right.add(rightTop,BorderLayout.NORTH);
//右中面板
text5=new JTextArea();
text5.setSize(60,120);
text5.setForeground(Color.red);
right.add(text5,BorderLayout.CENTER);
//右下面板
final JPanel rightBottom=new JPanel();
final FlowLayout flowLayout1=new FlowLayout();
flowLayout1.setHgap(5);
flowLayout1.setVgap(5);
rightBottom.setLayout(flowLayout1);
//字体
Font font1=new Font("楷体",Font.BOLD,18);
jButton1=new JButton();
jButton1.setText("保存");
jButton1.setBackground(Color.gray);
jButton1.setFont(font1);
jButton2=new JButton();
jButton2.setText("查看");
jButton2.setBackground(Color.gray);
jButton2.setFont(font1);
jButton3=new JButton();
jButton3.setText("清除");
jButton3.setBackground(Color.gray);
jButton3.setFont(font1);
rightBottom.add(jButton1);
rightBottom.add(jButton2);
rightBottom.add(jButton3);
right.add(rightBottom,BorderLayout.SOUTH);
//Spilitspan布局管理器
final JSplitPane hSplitPane=new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,left,right);//分为左右
hSplitPane.setDividerSize(5);
//窗口下最大的面板
JPanel panel=new JPanel();
BorderLayout borderLayout3=new BorderLayout();
panel.setLayout(borderLayout3);
panel.add(hSplitPane,BorderLayout.CENTER);
//总窗口
JFrame jFrame=new JFrame();
jFrame.setBounds(200,200,700,400);
jFrame.setTitle("计算器");
jFrame.setVisible(true);
BorderLayout borderLayout4=new BorderLayout();
jFrame.setLayout(borderLayout4);
jFrame.add(panel,BorderLayout.CENTER);
}
//添加监听器
void addMultiplyListenerButtons(ActionListener listener1)
{
for (int row=0 ;row<4;row++)
{
for (int col=0;col<5;col++)
{
buttons[row][col].addActionListener(listener1);//给左边的每一个按钮都添加监听器
}
}
System.out.println("左边按钮监听成功");
}
//
void addMultiplyListener(ActionListener listener2)
{
jButton1.addActionListener(listener2);
jButton2.addActionListener(listener2);
jButton3.addActionListener(listener2);
System.out.println("右边按钮监听成功");
}
//文本框1
void SetText11(String str1)
{
text1.setText(text1.getText()+str1);
}
//清除文本框1
void ClearText11()
{
text1.setText("");
}
//文本框2
void SetText22(String str2)
{
text2.setText(str2);
}
//清除文本框2
void ClearText22()
{
text2.setText("");
}
//文本框3
void SetText33(String str3)
{
text3.setText(text3.getText()+str3);
}
//清除文本框3
void ClearText33()
{
text3.setText("");
}
//文本框4
void SetText44(String str4)
{
text4.setText("="+str4);
}
//文本框5
void SetText55(String str5)
{
text5.setText(text5.getText()+"\n"+str5);
}
//清除文本框5
void ClearText55()
{
text5.setText("");
}
}
2.接着是Controller
package Swing.calculator; import javax.swing.*; import java.applet.AudioClip; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.net.URL; public class CalculatorController { private CalculatorWindow C_window; private CalculatorModel C_model; public CalculatorController(CalculatorWindow window, CalculatorModel model) {//之所以要传参,是因为在控制器需要使用相应对象和函数,但如果自己在内部创造进行调用相应对象和函数就不是和其他类操作的同一个对象 C_model = model; C_window = window; window.addMultiplyListener(new MultiplyListener()); window.addMultiplyListenerButtons(new MultiplyListenerButtons()); } //文本管理监听器 class MultiplyListener implements ActionListener { public void actionPerformed (ActionEvent e) { File file=new File("D:\\Idea\\IntelliJ IDEA Community Edition 2021.2.1\\idea-workplaces\\src\\Swing\\calculator","TextMessage"); String str=e.getActionCommand(); //查看事件 if (str.equals("查看")) { String text55; text55=C_model.FileInput(file);//拿到文件中的内容 C_window.SetText55(text55); System.out.println("查看监听事件发生"); } //清除事件 if (str.equals("清除")) { C_window.ClearText55(); System.out.println("清除监听事件被触发"); } //保存事件 if (str.equals("保存")) { String text=C_window.text5.getText(); C_model.FileOutput(text,file);//把内容放入文件中去 C_window.ClearText55(); System.out.println("保存监听事件被触发"); } //音效实现 if (!str.equals("")) MusicRealize2(new PlayMusic2()); } } //计算按钮监听器 class MultiplyListenerButtons implements ActionListener { @Override public void actionPerformed(ActionEvent e) { String str = e.getActionCommand(); //text1输入 if (C_window.text2.getText().equals("") && (str.equals("1") || str.equals("2") || str.equals("3") || str.equals("4") || str.equals("5") || str.equals("6") || str.equals("7") || str.equals("8") || str.equals("9") || str.equals("0"))) { C_window.SetText11(str); System.out.println("数字监听事件被触发"); } if (str.equals(".")&&C_window.text2.getText().equals("")) { String text11=C_window.text1.getText(); if (text11.contains(".")==false) //contains方法判断在一个字符串是否存在某一个字符 C_window.SetText11(str); else JOptionPane.showMessageDialog(null,"不能在同一个文本框内二次输入“.” !"); } //清除键 if (str.equals("c")) { if (C_window.text2.getText().equals("")) C_window.ClearText11(); else if (!C_window.text2.getText().equals("") && C_window.text3.getText().equals("")) C_window.ClearText22(); else if (!C_window.text2.getText().equals("") && !C_window.text3.getText().equals("")) C_window.ClearText33(); System.out.println("清除监听事件被触发"); } //调整数值正负号 if (str.equals("+/-")) { if (C_window.text2.getText().equals("")) { String s1 = C_window.text1.getText(); C_window.ClearText11(); C_window.SetText11(C_model.transfrom(s1)); } else if (!C_window.text2.getText().equals("") && !C_window.text3.getText().equals("")) { String s1 = C_window.text3.getText(); C_window.ClearText33(); C_window.SetText33(C_model.transfrom(s1)); } System.out.println("正负调整监听事件被触发"); } //退格事件 if (str.equals("退格")) { if (C_window.text2.getText().equals("") && !C_window.text1.getText().equals(""))//当text1的内容不为空时,且text2为空 { String s = C_window.text1.getText(); C_window.ClearText11(); C_window.SetText11(C_model.Back(s)); } else if (!C_window.text2.getText().equals("") && C_window.text3.getText().equals(""))//当text2不为空,且text3为空 { C_window.ClearText22(); } else if (!C_window.text2.getText().equals("") && !C_window.text3.getText().equals("")) { StringBuffer sb = new StringBuffer(C_window.text3.getText()); C_window.ClearText33(); C_window.SetText33(sb.substring(0, sb.length() - 1)); } System.out.println("退格监听事件被触发"); } //算术符号事件 if (str.equals("+") || str.equals("-") || str.equals("/") || str.equals("*")) { C_window.SetText22(str); System.out.println("算号监听事件被触发"); } //text3输入 if (!C_window.text2.getText().equals("") && (str.equals("1") || str.equals("2") || str.equals("3") || str.equals("4") || str.equals("5") || str.equals("6") || str.equals("7") || str.equals("8") || str.equals("9") || str.equals("0"))) { C_window.SetText33(str); System.out.println("数字监听事件被触发"); } if (str.equals(".")&&!C_window.text2.getText().equals("")) { String text33=C_window.text3.getText(); if (text33.contains(".")==false) C_window.SetText33(str); else JOptionPane.showMessageDialog(null,"不能在同一个文本框内二次输入“.” !"); } // =事件 if (str.equals("=")) { String str11 = C_window.text1.getText(); String str22 = C_window.text2.getText(); String str33 = C_window.text3.getText(); C_window.SetText44(C_model.Count(str11, str22, str33)); String value=new String(C_window.text1.getText()+C_window.text2.getText()+C_window.text3.getText()+C_window.text4.getText()); C_window.SetText55(value); //将计算过程一并打印进area System.out.println("算法监听事件被触发"); } //sqrt事件 if (str.equals("sqrt")) { if (C_window.text2.getText().equals("") && !C_window.text1.getText().equals("")) { String ss1 = C_window.text1.getText(); double tt1 = Double.parseDouble(ss1); tt1 = Math.sqrt(tt1); String sss1 = String.valueOf(tt1); C_window.SetText44(sss1); String value=new String("sqrt"+"("+ss1+")"+"="+sss1); C_window.SetText55(value); //将计算过程一并打印进area } else if (!C_window.text4.getText().equals("")) { String ss4 = C_window.text4.getText(); StringBuffer sb4 = new StringBuffer(ss4); String ssb4 = sb4.substring(1, sb4.length());//不要=符号 double ttb4 = Double.parseDouble(ssb4); ttb4 = Math.sqrt(ttb4); String sss4 = String.valueOf(ttb4); C_window.SetText44(sss4); String value=new String("sqrt"+"("+ssb4+")"+"="+sss4); C_window.SetText55(value); //将计算过程一并打印进area }else if (C_window.text1.getText().equals("")) JOptionPane.showMessageDialog(null,"出错"); System.out.println("开方监听事件被触发"); } //音效实现 if (!str.equals("")) MusicRealize1(new PlayMusic1()); } } //音效1 class PlayMusic1 implements Runnable{ URL u1=this.getClass().getClassLoader().getResource("Swing\\calculator\\ShuiDi.wav"); AudioClip co1=JApplet.newAudioClip(u1); public void run(){ co1.loop();//跳出指定循环 try{ Thread.sleep(400);//决定放出多长时间的音效(在指定的时间内暂停当前的线程操作,以毫秒为单位) System.out.println("呼呼呼呼呼呼呼"); co1.stop();//不关闭线程将会一直进行下去 }catch (InterruptedException e) { e.printStackTrace(); } } } //Music void MusicRealize1(PlayMusic1 play) { play.run(); System.out.println("播放音效成功"); } //音效2 class PlayMusic2 implements Runnable{ URL u1=this.getClass().getClassLoader().getResource("Swing\\calculator\\Bee.wav"); AudioClip co1=JApplet.newAudioClip(u1); public void run(){ co1.loop();//跳出指定循环 try{ Thread.sleep(400);//决定放出多长时间的音效 System.out.println("呼呼呼呼呼呼呼"); co1.stop(); }catch (InterruptedException e) { e.printStackTrace(); } } } //Music void MusicRealize2(PlayMusic2 play) { play.run(); System.out.println("播放音效成功"); } }
3.Model模型
package Swing.calculator;
import java.io.*;
public class CalculatorModel{
//构造函数
CalculatorModel()
{
System.out.println("这是计算器模型");
}
//正负号的转换
String transfrom(String str)
{
double t11=Double.parseDouble(str);
t11=t11*-1;
String s11=String.valueOf(t11);
return s11;
}
//计算
String Count(String str1,String str2,String str3)//传入计算数据 str22不变
{
double t1=Double.parseDouble(str1);
double t3=Double.parseDouble(str3);
String mark=str2;
double result=0;//保存答案
switch (mark)
{
case "+":
result=t1+t3;
break;
case "-":
result=t1-t3;
break;
case "*":
result=t1*t3;
break;
case "/":
result=t1/t3;
default:
break;
}
String s_result=String.valueOf(result);
return s_result;
}
//退格事件操作
String Back(String str)
{
StringBuffer sb=new StringBuffer(str);
return sb.substring(0,sb.length()-1);
}
//将text5中的内容放入文件夹
void FileOutput(String message,File file)
{
try{
if (!file.exists())
file.createNewFile();
int is1;
FileWriter fw=new FileWriter(file);
fw.write(message);//写入文件
fw.close();
FileReader fr=new FileReader(file);
System.out.println("写入文件中的内容是:");
while ((is1=fr.read())!=-1)
System.out.print((char) is1);
fr.close();
}catch (IOException e)
{
e.printStackTrace();
}
}
//文件内容放入到text5中//叫输入//叫读
String FileInput(File file)
{
char []ch=new char[100];
try{
int is2;
FileReader fr=new FileReader(file);
System.out.println("正在从文件中提取内容");
while ((is2=fr.read(ch))!=-1)//将内容放入字符数组
{
}
fr.close();
}catch (IOException e)
{
e.printStackTrace();
}
String message1=new String(ch);//字符数组转换为字符串
String message=message1.trim();//因为字符数组很长转化为字符串会有空格,需要消去
return message;
}
}
4.主页面
package Swing.calculator;
public class Calculator {
public static void main(String[] args) {
CalculatorModel model=new CalculatorModel();
CalculatorWindow window=new CalculatorWindow();
CalculatorController controller=new CalculatorController(window,model);
}
}
!!!有一点要注意的是Controller里面的音效使用的是.wav格式的音效文件,设计使用的是已经过时的AudioClip类包,如果大佬们有更好的办法解决,希望能分享一下,谢谢😀。
MVC模式的简要理解:【漫画编程】两分钟搞定 MVC 架构模式?新人up把编程和漫画结合在了一起!_哔哩哔哩_bilibili