2 回答
已采納

阿旭_
TA貢獻217條經(jīng)驗 獲得超353個贊
import?java.awt.Rectangle; import?javax.script.ScriptEngineManager; import?javax.script.ScriptException; import?javax.swing.JButton; import?javax.swing.JFrame; import?javax.swing.JLabel; import?javax.swing.JPanel; import?javax.swing.JTextField; public?class?Test67?{ public?static?void?main(String[]?args)?{ JFrame?frame?=?new?JFrame("計算任意公式"); JLabel?mJLabel_1?=?new?JLabel("請輸入要計算的公式,如:(3+2)*5"); mJLabel_1.setBounds(new?Rectangle(18,?53,?250,?38)); final?JLabel?mJLabel_2?=?new?JLabel(""); mJLabel_2.setBounds(new?Rectangle(18,?117,?250,?38)); final?JTextField?jf1?=?new?JTextField(20); jf1.setBounds(new?Rectangle(18,?91,?250,?25)); JButton?jb?=?new?JButton("確認"); jb.setBounds(new?Rectangle(18,?107?*?2?-?53,?150,?38)); jb.addActionListener(new?java.awt.event.ActionListener()?{ public?void?actionPerformed(java.awt.event.ActionEvent?e)?{ double?value?=?0; try?{ value?=?(double)?new?ScriptEngineManager().getEngineByName("js").eval(jf1.getText()); mJLabel_2.setText(""?+?value); }?catch?(ScriptException?e1)?{ e1.printStackTrace(); mJLabel_2.setText("請輸入正確公式"); } } }); JPanel?p?=?new?JPanel();?//?建立一個面板 p.add(mJLabel_1,?null); p.add(mJLabel_2,?null); p.add(jf1); p.setLayout(null); p.add(jb); frame.add(p);//?將面板添加到窗口 frame.setSize(300,?300);//?設(shè)置窗口大小 frame.setAlwaysOnTop(true);//?設(shè)置窗口始終在最上層 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//?設(shè)置默認的關(guān)閉操作,關(guān)閉窗口后退出程序 frame.setLocationRelativeTo(null);//?設(shè)置窗口居中 frame.setVisible(true);//?設(shè)置窗口可見,盡快調(diào)用paint()方法 frame.setResizable(false); } }

阿旭_
TA貢獻217條經(jīng)驗 獲得超353個贊
import?javax.script.ScriptEngine; import?javax.script.ScriptEngineManager; import?javax.script.ScriptException; import?javax.swing.JOptionPane; public?class?Test68?{ public?static?void?main(String[]?args)?{ String?str?=?(String)?JOptionPane.showInputDialog(null,?"請輸入要計算的公式,如:(3+2)*5",?"title",?JOptionPane.PLAIN_MESSAGE,?null,?null,?""); try?{ ScriptEngineManager?mScriptEngineManager?=?new?ScriptEngineManager(); ScriptEngine?mScriptEngine?=?mScriptEngineManager.getEngineByName("js"); double?value?=?(double)?mScriptEngine.eval(str); JOptionPane.showMessageDialog(null,?"結(jié)果為:"+value,?"標題",JOptionPane.PLAIN_MESSAGE);?? }?catch?(ScriptException?e1)?{ e1.printStackTrace(); JOptionPane.showMessageDialog(null,?"請輸入正確公式",?"標題",JOptionPane.ERROR_MESSAGE);?? } } }
添加回答
舉報
0/150
提交
取消