java簡(jiǎn)單實(shí)現(xiàn)計(jì)算器
本文實(shí)例為大家分享了java簡(jiǎn)單實(shí)現(xiàn)計(jì)算器的具體代碼,供大家參考,具體內(nèi)容如下
public class Calculator { static ScriptEngine jse = new ScriptEngineManager().getEngineByName('JavaScript'); private static void CreateFrame() { JFrame f = new JFrame('計(jì)算器'); f.setSize(600, 500); f.setVisible(true); f.setLayout(new BorderLayout()); f.setLayout(new GridLayout(6, 3)); f.setLocation(300, 150); JTextArea text = new JTextArea(20, 0); f.add(text, BorderLayout.NORTH); JButton but1 = new JButton('CE'); f.add(but1, BorderLayout.PAGE_END); String a[] = { '=', '7', '8', '9', '4', '5', '6', '1', '2', '3', '0', '+', '-', '*', '/', '.' }; JButton btn[] = new JButton[a.length]; for (int i = 0; i < a.length; i++) { btn[i] = new JButton(a[i]); f.add(btn[i]); } // 功能實(shí)現(xiàn) for (int i = 0; i < a.length; i++) { // 如果不是等于號(hào) if (i != 0) { int j = i; btn[i].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String s = btn[j].getText();// 獲取文本框內(nèi)容 text.append(s); } }); } else { // 如果點(diǎn)擊等于號(hào) btn[i].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { // 獲取文本框內(nèi)容 String gongshi = text.getText(); // 計(jì)算獲取的文本框中的內(nèi)容 String jieguo = jse.eval(gongshi).toString(); text.setText('='); text.setText(jieguo); } catch (Exception t) { text.setText(''); } } }); // CE按鈕 but1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (e.getSource() == but1) { text.setText(''); } } }); } } } public static void main(String[] args) { SwingUtilities.invokeLater(Calculator::CreateFrame); }}
效果圖:
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. php測(cè)試程序運(yùn)行速度和頁(yè)面執(zhí)行速度的代碼2. ASP中常用的22個(gè)FSO文件操作函數(shù)整理3. 三個(gè)不常見的 HTML5 實(shí)用新特性簡(jiǎn)介4. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報(bào)錯(cuò)問(wèn)題分析5. ASP調(diào)用WebService轉(zhuǎn)化成JSON數(shù)據(jù),附j(luò)son.min.asp6. SharePoint Server 2019新特性介紹7. React+umi+typeScript創(chuàng)建項(xiàng)目的過(guò)程8. 無(wú)線標(biāo)記語(yǔ)言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁(yè)9. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執(zhí)行過(guò)程解析10. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究
