java簡單實現(xiàn)計算器
本文實例為大家分享了java簡單實現(xiàn)計算器的具體代碼,供大家參考,具體內(nèi)容如下
public class Calculator { static ScriptEngine jse = new ScriptEngineManager().getEngineByName('JavaScript'); private static void CreateFrame() { JFrame f = new JFrame('計算器'); 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]); } // 功能實現(xiàn) for (int i = 0; i < a.length; i++) { // 如果不是等于號 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 { // 如果點擊等于號 btn[i].addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { // 獲取文本框內(nèi)容 String gongshi = text.getText(); // 計算獲取的文本框中的內(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); }}
效果圖:
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 低版本IE正常運行HTML5+CSS3網(wǎng)站的3種解決方案2. jsp實現(xiàn)局部刷新頁面、異步加載頁面的方法3. xml文件的結(jié)構(gòu)解讀第1/2頁4. Jsp中request的3個基礎(chǔ)實踐5. python GUI庫圖形界面開發(fā)之PyQt5工具欄控件QToolBar的詳細使用方法與實例6. 使用python修改文件并立即寫回到原始位置操作(inplace讀寫)7. python GUI庫圖形界面開發(fā)之PyQt5計數(shù)器控件QSpinBox詳細使用方法與實例8. Python填充任意顏色,不同算法時間差異分析說明9. Java map.getOrDefault()方法的用法詳解10. 什么是python的id函數(shù)
