[sunj小白瞎搞系列 一]

news/2024/9/23 17:13:38

小白瞎搞系列 1:

Introduction :

今天上JAVA课遇到了一个很蠢的作业,为什么蠢呢,其实我对JAVA不算很熟,关键还是,老师让我们用GUI写界面.....

没错,你没听错。都什么时间了!? 都2024.5.13 晚上 22:18分了,还在写GUI。好吧,不狡辩了,就是不想写

那为什么笔者要发呢, 夜深了发牢骚

作业是做一个Calculator(demo),说到demo,笔者顺便预告一下,笔者正在谋划一个大项目--从零实现操作系统demo版本

其实也还好了,有参考书,而且不光笔者在做,MIT,Tsinghua都在做,今天OS课上,老师还让我们做了HIT的OS一小节

确实深深的被OS吸引住了,虽然我主要major in AI,但是很好玩,以至于我论文都没看,代码也没跑

关于星期四要组会但我一篇论文都没看,代码没有跑,纯在瞎搞并且极度后悔的我

Code :

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;public class Experiment4_2_22 extends JFrame implements ActionListener {private JTextField outputField;private StringBuilder stringBuffer = new StringBuilder();JPanel jPanel = new JPanel();Experiment4_2_22() {setTitle("Calculate");setSize(500, 500);setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);setLocationRelativeTo(null);setLayout(new BorderLayout());outputField = new JTextField();outputField.setHorizontalAlignment(JTextField.CENTER);outputField.setEditable(false);add(outputField, BorderLayout.NORTH);jPanel.setLayout(new GridLayout(4, 4));String[] buttons = {"7", "8", "9", "/","4", "5", "6", "*","1", "2", "3", "+","0", ".", "=", "-"};for (String button : buttons) {JButton jButton = new JButton(button);jButton.addActionListener(this);jPanel.add(jButton);}add(jPanel);}@Overridepublic void actionPerformed(ActionEvent e) {String command = e.getActionCommand();if (command.equals("=")) {try {//用eval作为处理函数,减少冗杂double result = eval(stringBuffer.toString());outputField.setText(String.valueOf(result));stringBuffer.setLength(0);stringBuffer.append(result);} catch (ArithmeticException ex) {outputField.setText("Error");stringBuffer.setLength(0);}} else {stringBuffer.append(command);outputField.setText(stringBuffer.toString());}}private double eval(String expression) {// 如果表达式为空或长度为0,则返回0if (expression == null || expression.length() == 0) {return 0;}double res = 0;String[] tmp;// 根据运算符分割表达式并执行相应的计算if (expression.contains("+")) {tmp = expression.split("\\+");double n1 = Double.parseDouble(tmp[0]);double n2 = Double.parseDouble(tmp[1]);res = n1 + n2;} else if (expression.contains("-")) {tmp = expression.split("-");double n1 = Double.parseDouble(tmp[0]);double n2 = Double.parseDouble(tmp[1]);res = n1 - n2;} else if (expression.contains("*")) {tmp = expression.split("\\*");double n1 = Double.parseDouble(tmp[0]);double n2 = Double.parseDouble(tmp[1]);res = n1 * n2;} else if (expression.contains("/")) {tmp = expression.split("/");double n1 = Double.parseDouble(tmp[0]);double n2 = Double.parseDouble(tmp[1]);// 检查除数是否为0if (n2 != 0) {res = n1 / n2;} else {// 如果除数为0,返回0或者抛出异常,这里返回0res = 0;}} else {// 如果表达式中没有运算符,则直接将表达式解析为双精度浮点数res = Double.parseDouble(expression);}return res;}public static void main(String[] args) {SwingUtilities.invokeLater(() -> {Experiment4_2_22 e = new Experiment4_2_22();e.setVisible(true);});}
}

出于保险,读者还是解释一下把,防止你的语言基础不熟

JTextField outputField;

首先这个就是一个文本框, 叫JTextField

可以看到在source 里面他是一个swing的框架,说了跟没说一样

这里有几个比较重要的函数:第一个是setHorizontalAlignment,可以很明显的知道里面有很多方位词,所以肯定是用来判断方位的

第二个是setEditable,看不懂没关系,反正设为false就是不可修改的

接下来,是add这个函数

这个函数很清晰,意思就是在哪个component add‘,约束条件是哪个constraint

好啦,我铺垫了这么多基础知识,你应该能看懂一点我之前的代码啦。 加油!

接下来这个 JPanel的东西是用来布局的,注意他跟JFrame的布局是有区别的。JFrame是整体的,JPanel是用来把容器连在一起的,就例如,JButton要add在JPanel上。

JPanel jPanel = new JPanel();

(#`O′),别困了,给你个小任务

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);

查查这两行代码作用于谁?代码是什么意思?

再查查

new GridLayout()
new BorderLayout()

是什么意思?

好啦,你查完了吧,我们继续吧。

我们看到这一段。

我们说说处理事件的逻辑,我们首先用getActionCommand()去得到动作对象的字符串,什么东西?

LLM讲的很好。我这里顺便也问了getSource()与之的区别,getSource()是什么?谷歌吧。 _

String command = e.getActionCommand();
if (command.equals("=")) {try {//用eval作为处理函数,减少冗杂double result = eval(stringBuffer.toString());outputField.setText(String.valueOf(result));stringBuffer.setLength(0);stringBuffer.append(result);} catch (ArithmeticException ex) {outputField.setText("Error");stringBuffer.setLength(0);}
} else {stringBuffer.append(command);outputField.setText(stringBuffer.toString());
}

这里我们是要做一个计算器,那肯定要用stringBuffer去做,因为他是个动态字符串,JAVA不像Cpp,他的string是个常值,所以我们这里得用stringBuffer

然后在去转string去输出到outputField。假如没遇到"="之前,那就一直加,显示一直打出来,遇到了就进行处理,每次处理完,就设置stringBuffer长度为0,即是设置为空值的意思,然后具体怎么实现呢,请看eval函数,很简单的,我就不讲解了。

private double eval(String expression) {// 如果表达式为空或长度为0,则返回0if (expression == null || expression.length() == 0) {return 0;}double res = 0;String[] tmp;// 根据运算符分割表达式并执行相应的计算if (expression.contains("+")) {tmp = expression.split("\\+");double n1 = Double.parseDouble(tmp[0]);double n2 = Double.parseDouble(tmp[1]);res = n1 + n2;} else if (expression.contains("-")) {tmp = expression.split("-");double n1 = Double.parseDouble(tmp[0]);double n2 = Double.parseDouble(tmp[1]);res = n1 - n2;} else if (expression.contains("*")) {tmp = expression.split("\\*");double n1 = Double.parseDouble(tmp[0]);double n2 = Double.parseDouble(tmp[1]);res = n1 * n2;} else if (expression.contains("/")) {tmp = expression.split("/");double n1 = Double.parseDouble(tmp[0]);double n2 = Double.parseDouble(tmp[1]);// 检查除数是否为0if (n2 != 0) {res = n1 / n2;} else {// 如果除数为0,返回0或者抛出异常,这里返回0res = 0;}} else {// 如果表达式中没有运算符,则直接将表达式解析为双精度浮点数res = Double.parseDouble(expression);}return res;
}

对了,最后说一点,

SwingUtilities.invokeLater(() -> {Experiment4_2_22 e = new Experiment4_2_22();e.setVisible(true);
});

因为我们进行GUI编程的时候,很多时候会多线程操作,会有一点安全问题,具体请谷歌,蛮复杂的。

所以我们得用SwingUtilities.invokeLater()去保证安全。

invokeLater(接受一个对象),一旦执行,这个任务会被放入事件队列中,等待事件分发线程去执行。这样就确保了在正确的线程上执行 GUI 相关的操作,避免了多线程导致的并发访问问题。

至此全篇结束

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.ryyt.cn/news/31172.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈,一经查实,立即删除!

相关文章

软考-官方模拟考试-务必参加!

模拟练习时间 模拟练习平台开放时间:2024年5月13日 9:00 至 5月23日 17:00,报名参加考试的考生可在该时段内自愿进行网上模拟平台练习。 模拟考试时间只开放10天时间。 官方公告原文:https://www.ruankao.org.cn/article/content/2405071807085639092455991 模拟考试系统入…

hive on spark

1 Hive的执行引擎Hive:专业的数仓软件,可以高效的读写和管理数据集。 Hive的运行原理:① hive主要是写HQL的 (类SQL,相似度90%,剩下的10%就是HQL里面一些独有的语法)② 写的HQL会根据不同的计算引擎翻译成不同的代码2 数仓搭建技术选型Spark On Hive:基于Hive的Spark…

Windows computer File share Settings

1. Search for "Manage advanced sharing settings" in the Windows lower left corner and click the result. As shown below ①, ② 2.Then select the two items in the pop-up page, as shown in the figure ③ 3.Then search for "Turn Windows feature…

2024 AI中转计费平台系统源码

简介:2024 AI中转计费平台系统源码 图片: 点击下载

使用joinjs绘制流程图(八)-实战-绘制流程图+节点路径自定义

效果图代码 <template><div class="app"><div ref="myholder" id="paper"></div></div> </template><script> import * as joint from @joint/core import $ from jquery export default {data() {re…

什么是数据中心?有哪些类型?如何工作?

数据中心是一种物理设施,提供操作程序的计算能力,处理信息的存储,以及将人们连接到执行任务和支持企业运营所需的资源的网络。一、什么是数据中心? 数据中心是一个房间、一座建筑物或一组建筑物,用于容纳后端计算机系统,设有用户界面和冷却能力、物理安全、网络设备等支持…

万事通,专精部分领域的多功能 Transformer 智能体

介绍 我们很高兴分享“万事通”(Jack of All Trades,简称 JAT) 项目,该项目旨在朝着通用智能体的方向发展。该项目最初是作为对 Gato (Reed 等,2022 年) 工作的公开复现启动的,Gato 提出训练一种能够执行视觉与语言以及决策任务的 Transformer。于是我们首先构建了 Gato 数…

WSL常用命令

WSL常用命令 WSL重启WSL中reboot和shutdown都无法使用, 我直接使用win下的WSL命令来实现重启的.wsl --shutdown # 关闭所有wsl wsl -l -v # 检查是否关闭关闭后再启动wsl即可. GUI程序中文字体显示为方块问题错误如下:检查已安装的字体$ fc-list # 若没有此命令,需先安装…