Java Swing Calculator program not running. It has 0 errors

Reply

Join Date: Jan 2006
Posts: 34
Reputation: hemanthjava is an unknown quantity at this point 
Solved Threads: 0
hemanthjava hemanthjava is offline Offline
Light Poster

Java Swing Calculator program not running. It has 0 errors

 
0
  #1
Oct 14th, 2006
  1. /*
  2. Java Swing Calculator
  3. */
  4.  
  5. import java.awt.BorderLayout;
  6. import java.awt.Color;
  7. import java.awt.Container;
  8. import java.awt.FlowLayout;
  9. import java.awt.Font;
  10. import java.awt.GridLayout;
  11. import java.awt.Window;
  12. import java.awt.event.ActionEvent;
  13. import java.awt.event.ActionListener;
  14. import java.awt.event.WindowAdapter;
  15. import java.awt.event.WindowEvent;
  16.  
  17. import javax.swing.JButton;
  18. import javax.swing.JDialog;
  19. import javax.swing.JFrame;
  20. import javax.swing.JLabel;
  21. import javax.swing.JMenu;
  22. import javax.swing.JMenuBar;
  23. import javax.swing.JMenuItem;
  24. import javax.swing.JPanel;
  25. import javax.swing.JTextArea;
  26.  
  27. public class Calculator extends JFrame implements ActionListener
  28. {
  29. // Variables
  30. final int MAX_INPUT_LENGTH = 20;
  31. final int INPUT_MODE = 0;
  32. final int RESULT_MODE = 1;
  33. final int ERROR_MODE = 2;
  34. int displayMode;
  35.  
  36. boolean clearOnNextDigit, percent;
  37. double lastNumber;
  38. String lastOperator;
  39.  
  40. private JMenu jmenuFile, jmenuEdit, jmenuView, jmenuHelp;
  41. private JMenuItem jmenuitemExit, jmenuitemCopy, jmenuitemPaste, jmenuitemStd,
  42. jmenuitemSci, jmenuitemDigitGrp, jmenuitemAbout;
  43. private JDialog dialog;
  44.  
  45. private JLabel display;
  46. private JButton button[];
  47. private JPanel masterPanel;
  48.  
  49. Font f12 = new Font("Times New Roman", 0, 12);
  50. Font f121 = new Font("Times New Roman", 1, 12);
  51.  
  52. // Constructor
  53. public Calculator()
  54. {
  55.  
  56. //Set Up the JMenuBar
  57. jmenuFile = new JMenu("File");
  58. jmenuFile.setFont(f121);
  59.  
  60. jmenuitemExit = new JMenuItem("Exit");
  61. jmenuitemExit.setFont(f12);
  62. jmenuFile.add(jmenuitemExit);
  63.  
  64. jmenuEdit = new JMenu("Edit");
  65. jmenuEdit.setFont(f121);
  66.  
  67. jmenuitemCopy = new JMenuItem("Copy");
  68. jmenuitemCopy.setFont(f12);
  69.  
  70. jmenuitemPaste = new JMenuItem("Paste");
  71. jmenuitemPaste.setFont(f12);
  72. jmenuEdit.add(jmenuitemCopy);
  73. jmenuEdit.add(jmenuitemPaste);
  74.  
  75. jmenuView = new JMenu("View");
  76. jmenuView.setFont(f121);
  77.  
  78. jmenuitemStd = new JMenuItem("Standard");
  79. jmenuitemStd.setFont(f12);
  80.  
  81. jmenuitemSci = new JMenuItem("Scientific");
  82. jmenuitemSci.setFont(f12);
  83.  
  84. jmenuitemDigitGrp = new JMenuItem("Digit Grouping");
  85. jmenuitemDigitGrp.setFont(f12);
  86. jmenuView.add(jmenuitemStd);
  87. jmenuView.add(jmenuitemSci);
  88. jmenuView.addSeparator();
  89. jmenuView.add(jmenuitemDigitGrp);
  90.  
  91. jmenuHelp = new JMenu("Help");
  92. jmenuHelp.setFont(f121);
  93.  
  94. jmenuitemAbout = new JMenuItem("About Calculator");
  95. jmenuitemAbout.setFont(f12);
  96. jmenuHelp.add(jmenuitemAbout);
  97.  
  98. JMenuBar mb = new JMenuBar();
  99. mb.add(jmenuFile);
  100. mb.add(jmenuEdit);
  101. mb.add(jmenuView);
  102. // mb.setHelpMenu(jmenuHelp);
  103. setJMenuBar(mb);
  104.  
  105. //Set frame layout manager
  106.  
  107. setBackground(Color.gray);
  108.  
  109. /*
  110.   * Font(String name, int style, int size)
  111. Creates a new Font from the specified name, style and point size.
  112.   */
  113.  
  114.  
  115. //adds menubar to frame (end)
  116.  
  117. masterPanel = new JPanel();
  118.  
  119. display = new JLabel("0");
  120. display.setAlignmentX(JLabel.RIGHT);
  121. display.setBackground(Color.cyan);
  122.  
  123. Container contentPane = getContentPane();
  124.  
  125. // Add components to frame
  126. contentPane.add(display, BorderLayout.NORTH);
  127.  
  128. button = new JButton[23];
  129.  
  130. JPanel backSpace = new JPanel();
  131. backSpace.setLayout(new GridLayout(1, 1, 2, 2));
  132.  
  133. button[20] = new JButton("Backspace");
  134. backSpace.add(button[20]);
  135.  
  136. JPanel control = new JPanel();
  137. control.setLayout(new GridLayout(1, 2, 2 ,2));
  138.  
  139. button[21] = new JButton(" CE ");
  140. button[22] = new JButton("C");
  141.  
  142. control.add(button[21]);
  143. control.add(button[22]);
  144.  
  145. JPanel keyPad = new JPanel(); // container for buttons
  146.  
  147. // Create numeric buttons
  148. for (int i=0; i<=9; i++)
  149. {
  150. // set each button label to the value of index
  151. button[i] = new JButton(String.valueOf(i));
  152. }
  153.  
  154. // Create operator buttons
  155. button[10] = new JButton("+/-");
  156. button[11] = new JButton(".");
  157. button[12] = new JButton("=");
  158. button[13] = new JButton("/");
  159. button[14] = new JButton("*");
  160. button[15] = new JButton("-");
  161. button[16] = new JButton("+");
  162. button[17] = new JButton("sqrt");
  163. button[18] = new JButton("1/x");
  164. button[19] = new JButton("%");
  165.  
  166. for (int i=0; i<button.length; i++)
  167. {
  168. button[i].setFont(f12);
  169.  
  170. if (i<13)
  171. button[i].setForeground(Color.blue);
  172.  
  173. else
  174. button[i].setForeground(Color.red);
  175. }
  176.  
  177. // Set panel layout manager for a 4 by 5 grid
  178. keyPad.setLayout(new GridLayout(4, 5, 2, 2));
  179.  
  180. //Add buttons to keypad panel starting at top left
  181. // First row
  182. for(int i=7; i<=9; i++)
  183. {
  184. //adds buttons 7,8,9 and /
  185. keyPad.add(button[i]);
  186. }
  187.  
  188. // add button / and sqrt
  189. keyPad.add(button[13]);
  190. keyPad.add(button[17]);
  191.  
  192. // Second row
  193. for(int i=4; i<=6; i++)
  194. {
  195. //adds buttons 4,5,6
  196. keyPad.add(button[i]);
  197. }
  198.  
  199. // add button * and x^2
  200. keyPad.add(button[14]);
  201. keyPad.add(button[18]);
  202.  
  203. // Third row
  204. for( int i=1; i<=3; i++)
  205. {
  206. // add buttons 1,2,3
  207. keyPad.add(button[i]);
  208. }
  209.  
  210. //adds button - and %
  211. keyPad.add(button[15]);
  212. keyPad.add(button[19]);
  213.  
  214. //Fourth Row
  215. // add 0, +/-, ., +, and =
  216. keyPad.add(button[0]);
  217. keyPad.add(button[10]);
  218. keyPad.add(button[11]);
  219. keyPad.add(button[16]);
  220. keyPad.add(button[12]);
  221.  
  222. masterPanel.setLayout(new BorderLayout());
  223. masterPanel.add(backSpace, BorderLayout.WEST);
  224. masterPanel.add(control, BorderLayout.EAST);
  225. masterPanel.add(keyPad, BorderLayout.SOUTH);
  226.  
  227. // Add components to frame
  228. contentPane.add(masterPanel, BorderLayout.SOUTH);
  229. requestFocus();
  230.  
  231. //activate ActionListener
  232. for (int i=0; i<button.length; i++)
  233. {
  234. button[i].addActionListener(this);
  235. }
  236.  
  237. jmenuitemAbout.addActionListener(this);
  238. jmenuitemExit.addActionListener(this);
  239.  
  240. clearAll();
  241.  
  242. //add WindowListener for closing frame and ending program
  243. addWindowListener(new WindowAdapter()
  244. {
  245. public void windowClosing(WindowEvent e)
  246. {
  247. Window theWindow = e.getWindow();
  248. theWindow.dispose();
  249. }
  250.  
  251. public void windowClosed(WindowEvent e)
  252. {
  253. System.exit(0);
  254. }
  255. }
  256. &nbsp;);
  257. }
  258.  
  259. // Perform action
  260. public void actionPerformed(ActionEvent e)
  261. {
  262. double result = 0;
  263.  
  264. if(e.getSource() == jmenuitemAbout)
  265. {
  266. System.out.println("Starting About Calculator window...");
  267. JDialog dlg = new CustomDialog(this, "About Calculator", true);
  268. dlg.setVisible(true);
  269. }
  270.  
  271. else if(e.getSource() == jmenuitemExit)
  272. {
  273. System.out.println("Quitting Calculator window...");
  274. System.exit(0);
  275. }
  276.  
  277. // Search for the button pressed until end of array or key found
  278. for (int i=0; i<button.length; i++)
  279. {
  280. if(e.getSource() == button[i])
  281. {
  282. switch(i)
  283. {
  284. case 0:
  285. addDigit(i);
  286. break;
  287.  
  288. case 1:
  289. addDigit(i);
  290. break;
  291.  
  292. case 2:
  293. addDigit(i);
  294. break;
  295.  
  296. case 3:
  297. addDigit(i);
  298. break;
  299.  
  300. case 4:
  301. addDigit(i);
  302. break;
  303.  
  304. case 5:
  305. addDigit(i);
  306. break;
  307.  
  308. case 6:
  309. addDigit(i);
  310. break;
  311.  
  312. case 7:
  313. addDigit(i);
  314. break;
  315.  
  316. case 8:
  317. addDigit(i);
  318. break;
  319.  
  320. case 9:
  321. addDigit(i);
  322. break;
  323.  
  324. case 10: // +/-
  325. processSignChange();
  326. break;
  327.  
  328. case 11: // decimal point
  329. addDecimalPoint();
  330. break;
  331.  
  332. case 12: // =
  333. processEquals();
  334. break;
  335.  
  336. case 13: // divide
  337. processOperator("/");
  338. break;
  339.  
  340. case 14: // *
  341. processOperator("*");
  342. break;
  343.  
  344. case 15: // -
  345. processOperator("-");
  346. break;
  347.  
  348. case 16: // +
  349. processOperator("+");
  350. break;
  351.  
  352. case 17: // sqrt
  353. if (displayMode != ERROR_MODE)
  354. {
  355. try
  356. {
  357. if (getDisplayString().indexOf("-") == 0)
  358. displayError("Invalid input for function!");
  359.  
  360. result = Math.sqrt(getNumberInDisplay());
  361. displayResult(result);
  362. }
  363.  
  364. catch(Exception ex)
  365. {
  366. displayError("Invalid input for function!");
  367. displayMode = ERROR_MODE;
  368. }
  369. }
  370. break;
  371.  
  372. case 18: // 1/x
  373. if (displayMode != ERROR_MODE)
  374. {
  375. try
  376. {
  377. if (getNumberInDisplay() == 0)
  378. displayError("Cannot divide by zero!");
  379.  
  380. result = 1 / getNumberInDisplay();
  381. displayResult(result);
  382. }
  383.  
  384. catch(Exception ex)
  385. {
  386. displayError("Cannot divide by zero!");
  387. displayMode = ERROR_MODE;
  388. }
  389. }
  390. break;
  391.  
  392. case 19: // %
  393. if (displayMode != ERROR_MODE)
  394. {
  395. try
  396. {
  397. result = getNumberInDisplay() / 100;
  398. displayResult(result);
  399. }
  400.  
  401. catch(Exception ex)
  402. {
  403. displayError("Invalid input for function!");
  404. displayMode = ERROR_MODE;
  405. }
  406. }
  407. break;
  408.  
  409. case 20: // backspace
  410. if (displayMode != ERROR_MODE)
  411. {
  412. setDisplayString(getDisplayString().substring(0,
  413. getDisplayString().length() - 1));
  414.  
  415. if (getDisplayString().length() < 1)
  416. setDisplayString("0");
  417. }
  418. break;
  419.  
  420. case 21: // CE
  421. clearExisting();
  422. break;
  423.  
  424. case 22: // C
  425. clearAll();
  426. break;
  427. }
  428. }
  429. }
  430. }
  431.  
  432. void setDisplayString(String s)
  433. {
  434. display.setText(s);
  435. }
  436.  
  437. String getDisplayString ()
  438. {
  439. return display.getText();
  440. }
  441.  
  442. void addDigit(int digit)
  443. {
  444. if (clearOnNextDigit)
  445. setDisplayString("");
  446.  
  447. String inputString = getDisplayString();
  448.  
  449. if (inputString.indexOf("0") == 0)
  450. {
  451. inputString = inputString.substring(1);
  452. }
  453.  
  454. if ((!inputString.equals("0") || digit > 0) && inputString.length() < MAX_INPUT_LENGTH)
  455. {
  456. setDisplayString(inputString + digit);
  457. }
  458.  
  459.  
  460. displayMode = INPUT_MODE;
  461. clearOnNextDigit = false;
  462. }
  463.  
  464. void addDecimalPoint()
  465. {
  466. displayMode = INPUT_MODE;
  467.  
  468. if (clearOnNextDigit)
  469. setDisplayString("");
  470.  
  471. String inputString = getDisplayString();
  472.  
  473. // If the input string already contains a decimal point, don't
  474. // do anything to it.
  475. if (inputString.indexOf(".") < 0)
  476. setDisplayString(new String(inputString + "."));
  477. }
  478.  
  479. void processSignChange()
  480. {
  481. if (displayMode == INPUT_MODE)
  482. {
  483. String input = getDisplayString();
  484.  
  485. if (input.length() > 0 && !input.equals("0"))
  486. {
  487. if (input.indexOf("-") == 0)
  488. setDisplayString(input.substring(1));
  489.  
  490. else
  491. setDisplayString("-" + input);
  492. }
  493.  
  494. }
  495.  
  496. else if (displayMode == RESULT_MODE)
  497. {
  498. double numberInDisplay = getNumberInDisplay();
  499.  
  500. if (numberInDisplay != 0)
  501. displayResult(-numberInDisplay);
  502. }
  503. }
  504.  
  505. void clearAll()
  506. {
  507. setDisplayString("0");
  508. lastOperator = "0";
  509. lastNumber = 0;
  510. displayMode = INPUT_MODE;
  511. clearOnNextDigit = true;
  512. }
  513.  
  514. void clearExisting()
  515. {
  516. setDisplayString("0");
  517. clearOnNextDigit = true;
  518. displayMode = INPUT_MODE;
  519. }
  520.  
  521. double getNumberInDisplay()
  522. {
  523. String input = display.getText();
  524. return Double.parseDouble(input);
  525. }
  526.  
  527. void processOperator(String op)
  528. {
  529. if (displayMode != ERROR_MODE)
  530. {
  531. double numberInDisplay = getNumberInDisplay();
  532.  
  533. if (!lastOperator.equals("0"))
  534. {
  535. try
  536. {
  537. double result = processLastOperator();
  538. displayResult(result);
  539. lastNumber = result;
  540. }
  541.  
  542. catch (DivideByZeroException e)
  543. {
  544. }
  545. }
  546.  
  547. else
  548. {
  549. lastNumber = numberInDisplay;
  550. }
  551.  
  552. clearOnNextDigit = true;
  553. lastOperator = op;
  554. }
  555. }
  556.  
  557. void processEquals()
  558. {
  559. double result = 0;
  560.  
  561. if (displayMode != ERROR_MODE)
  562. {
  563. try
  564. {
  565. result = processLastOperator();
  566.  
  567. //// if (result == 0)
  568. //// setDisplayString("" + Double.parseDouble(getDisplayString()));
  569. //
  570. // if (result == 0)
  571. // displayResult(result);
  572. //
  573. // else
  574. displayResult(result);
  575. }
  576.  
  577. catch (DivideByZeroException e)
  578. {
  579. displayError("Cannot divide by zero!");
  580. }
  581.  
  582. lastOperator = "0";
  583. }
  584. }
  585.  
  586. double processLastOperator() throws DivideByZeroException
  587. {
  588. double result = 0;
  589. double numberInDisplay = getNumberInDisplay();
  590.  
  591. if (lastOperator.equals("/"))
  592. {
  593. if (numberInDisplay == 0)
  594. throw (new DivideByZeroException());
  595.  
  596. result = lastNumber / numberInDisplay;
  597. }
  598.  
  599. if (lastOperator.equals("*"))
  600. result = lastNumber * numberInDisplay;
  601.  
  602. if (lastOperator.equals("-"))
  603. result = lastNumber - numberInDisplay;
  604.  
  605. if (lastOperator.equals("+"))
  606. result = lastNumber + numberInDisplay;
  607.  
  608. return result;
  609. }
  610.  
  611. void displayResult(double result)
  612. {
  613. setDisplayString(Double.toString(result));
  614. lastNumber = result;
  615. displayMode = RESULT_MODE;
  616. clearOnNextDigit = true;
  617. }
  618.  
  619. void displayError(String errorMessage)
  620. {
  621. setDisplayString(errorMessage);
  622. lastNumber = 0;
  623. displayMode = ERROR_MODE;
  624. clearOnNextDigit = true;
  625. }
  626.  
  627. public static void main(String args[])
  628. {
  629. Calculator calci = new Calculator();
  630. Container contentPane = calci.getContentPane();
  631. contentPane.setLayout(new BorderLayout());
  632. calci.setTitle("Java Swing Calculator");
  633. contentPane.setSize(241, 217);
  634. contentPane.setLocation(400, 250);
  635. contentPane.setVisible(true);
  636. calci.setResizable(false);
  637. }
  638.  
  639. }
  640.  
  641. class DivideByZeroException extends Exception
  642. {
  643. public DivideByZeroException()
  644. {
  645. super();
  646. }
  647.  
  648. public DivideByZeroException(String s)
  649. {
  650. super(s);
  651. }
  652. }
  653.  
  654. class CustomDialog extends JDialog implements ActionListener
  655. {
  656. JButton OK;
  657.  
  658. CustomDialog(JFrame parent, String title, boolean modal)
  659. {
  660. super(parent, title, modal);
  661. setBackground(Color.black);
  662.  
  663. JPanel p1 = new JPanel(new FlowLayout(FlowLayout.CENTER));
  664.  
  665.  
  666. StringBuffer text = new StringBuffer();
  667. text.append("Calculator Information\n\n");
  668. text.append("Developer: Canh Doan\n");
  669. text.append("Date: 09/16/03\n");
  670. text.append("Version: 1.0");
  671.  
  672. JTextArea aboutCalc = new JTextArea(5, 21);
  673. aboutCalc.setText(text.toString());
  674. aboutCalc.setFont(new Font("Times New Roman", 1, 16));
  675. aboutCalc.setEditable(false);
  676. aboutCalc.setBackground(Color.yellow);
  677.  
  678. p1.add(aboutCalc);
  679. p1.setBackground(Color.red);
  680. add(p1, BorderLayout.CENTER);
  681.  
  682. JPanel p2 = new JPanel(new FlowLayout(FlowLayout.CENTER));
  683. OK = new JButton(" OK ");
  684. OK.setFont(new Font("Times New Roman", 1, 14));
  685. OK.setBackground(Color.white);
  686. OK.setForeground(Color.blue);
  687. OK.addActionListener(this);
  688.  
  689. p2.add(OK);
  690. p2.setBackground(Color.blue);
  691. add(p2, BorderLayout.SOUTH);
  692.  
  693. setLocation(408, 270);
  694. setResizable(false);
  695.  
  696. addWindowListener(new WindowAdapter()
  697. {
  698. public void windowClosing(WindowEvent e)
  699. {
  700. Window aboutDialog = e.getWindow();
  701. aboutDialog.dispose();
  702. }
  703. }
  704. &nbsp;);
  705.  
  706. pack();
  707. }
  708.  
  709. public void actionPerformed(ActionEvent e)
  710. {
  711. if(e.getSource() == OK)
  712. {
  713. System.out.println("Quitting About Calculator window...");
  714. this.dispose();
  715. }
  716. }
  717.  
  718. }
Regards,
Hemanth
Last edited by cscgal; Oct 14th, 2006 at 9:07 pm. Reason: Fake signature removed and code tags added
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 101
Reputation: cms271828 is an unknown quantity at this point 
Solved Threads: 4
cms271828 cms271828 is offline Offline
Junior Poster

Re: Java Swing Calculator program not running. It has 0 errors

 
1
  #2
Oct 14th, 2006
In your main method, where you've got...

contentPane.setSize(241, 217);
contentPane.setLocation(400, 250);
contentPane.setVisible(true);

Change it to calci. instead of contentPane.
Since you need to apply it to the JFrame, not its contentPane.
Reply With Quote Quick reply to this message  
Join Date: Jan 2006
Posts: 34
Reputation: hemanthjava is an unknown quantity at this point 
Solved Threads: 0
hemanthjava hemanthjava is offline Offline
Light Poster

Re: Java Swing Calculator program not running. It has 0 errors

 
0
  #3
Oct 14th, 2006
Hi ,
Thank you very much for that changes. I tried running the same above program after changing the contentpane to calci. When I run the program I am only getting the outerframe as the output. The inner master panel and all the buttons are not being displayed. No cpmponents are being added. Can you help me with it.

Regards,
Hemanth
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 101
Reputation: cms271828 is an unknown quantity at this point 
Solved Threads: 4
cms271828 cms271828 is offline Offline
Junior Poster

Re: Java Swing Calculator program not running. It has 0 errors

 
0
  #4
Oct 15th, 2006
Yeh,I'll take a look, I did run it (after the change I mentioned) and noticed there was no calculator, but I thought maybe that was how far you got.
I'll take a look at it now, I'll reply soon.
Reply With Quote Quick reply to this message  
Join Date: Jan 2006
Posts: 34
Reputation: hemanthjava is an unknown quantity at this point 
Solved Threads: 0
hemanthjava hemanthjava is offline Offline
Light Poster

Re: Java Swing Calculator program not running. It has 0 errors

 
0
  #5
Oct 15th, 2006
Hi thanks dude. I got to know what the probelm was. My calculator is working. Thank you for taking so much time.... I had set layout manager again in main, after doing it once in the constructor. Thank you so much for your time.
Last edited by hemanthjava; Oct 15th, 2006 at 12:30 am. Reason: Some detail added
Reply With Quote Quick reply to this message  
Join Date: Oct 2006
Posts: 101
Reputation: cms271828 is an unknown quantity at this point 
Solved Threads: 4
cms271828 cms271828 is offline Offline
Junior Poster

Re: Java Swing Calculator program not running. It has 0 errors

 
0
  #6
Oct 15th, 2006
Yeh, I just fixed it too, you just needed to put the

setSize(241, 217);
setLocation(400, 250);
setVisible(true);
in your constructor instead, not sure why you can't do it like it was though, hmmm.

Ok, ignore what I just said above, I just read you reset the layout, which is why that was happening, but putting that in constructor is what I usually do.
Last edited by cms271828; Oct 15th, 2006 at 12:43 am.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC