Question

In: Computer Science

In this task you will complete the calculation and implement the Clear button. 1. When an...

In this task you will complete the calculation and implement the Clear button.

1. When an arithmetic operator is pressed retrieve the String from the JLabel, parse it to a Float value and assign it to a variable num1. Consult the Java API and the textbook to workout how to convert a String to a Float. Hint: use the same structure as when we convert a String to an Integer.

2. You should retrieve the operator and store it in a char variable op.

3. Follow the same procedure as before to input the second number. When the user presses the equals button retrieve the String from the label and assign the Float to a variable num2. Calculate the result and display it on the JLabel.

4. To complete the calculation define a private float method called calculate that accepts 3 parameters (char op, float num1, float num2). Use a switch statement to determine what operation to do and then return the result from the calculation.

5. Finally, if the user presses the Clear button then set num1 and num2 to 0 and set the text of the JLabel to 0.

import javax.swing.JFrame;
import javax.swing.*;
import java.awt.event.*;
/*
* Driver Class for the Calcultor
*
* @author
*/
public class CalculatorDriver {
public static void main(String[] args) {
// create JFrame object
JFrame frame=new JFrame("Simple Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// create object of CalculatorPanel class
CalculatorPanel panel=new CalculatorPanel();
frame.getContentPane().add(panel); // add panel into frame
frame.pack();
frame.setResizable(false); // frame should not be resizable
frame.setLocation(400,300); // set location of frame
frame.setVisible(true); // make frame visible
}
}

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

/**
* The calculator panel
* @author
*/
public class CalculatorPanel extends JPanel {
private static final long serialVersionUID = 1L;
private static final int CALC_WIDTH=250;
private static final int CALC_HEIGHT=225;

public CalculatorPanel() {
setLayout(new BorderLayout());
setBackground(Color.lightGray); // create the input/output panel
result = 0; // result variable of label
lastCommand = "=";
start = true;

// add the display
resultLabel = new JLabel("0", SwingConstants.RIGHT); // set the JLabel to RIGHT
resultLabel.setFont(new Font("Helvetica", Font.BOLD, 40)); // set the font size
add(resultLabel, BorderLayout.NORTH); // set the border layout to NORTH

// Action listener creates
ActionListener insert = new InsertAction();
ActionListener command = new CommandAction();

// CREATE A LAYOUT OF THE BUTTONS 4X4 grid
panel = new JPanel();
panel.setLayout(new GridLayout(4, 4)); //set the 4x4 grid
panel.setBackground(Color.DARK_GRAY); //set the background color

// add the button text and assign the action
addButton("7", insert);
addButton("8", insert);
addButton("9", insert);
addButton("/", command);
  
addButton("4", insert);
addButton("5", insert);
addButton("6", insert);
addButton("*", command);
  
addButton("1", insert);
addButton("2", insert);
addButton("3", insert);
addButton("-", command);

addButton("0", insert);
addButton(".", insert);
addButton("=", command);
addButton("+", command);
  
add(panel, BorderLayout.CENTER); // set the panel to center
}
  
// add button
private void addButton(String label, ActionListener listener) {
JButton button = new JButton(label);
button.setPreferredSize(new Dimension(55,30)); //set the button size
button.setFont(new Font("Helvetica", Font.BOLD, 15)); // set the font size
button.setForeground(Color.BLUE); //set the font color to blue
button.addActionListener(listener); // add the action listener
panel.add(button); // add the button to the panel
}

  
private class InsertAction implements ActionListener {
public void actionPerformed(ActionEvent event) {
String input = event.getActionCommand();
if (start) {
resultLabel.setText("");
start = false;
}
resultLabel.setText(resultLabel.getText() + input); //display the text to the label
}
}


private class CommandAction implements ActionListener {
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();

if (start) {
if (command.equals("-")) {
resultLabel.setText(command);
start = false;
} else
lastCommand = command;
} else {
calculate(Double.parseDouble(resultLabel.getText()));
lastCommand = command;
start = true;
}
}
}

// method that calculate the result of two inputs
public void calculate(double x) {
if (lastCommand.equals("+"))
result += x; // add
else if (lastCommand.equals("-"))
result -= x; // subtract
else if (lastCommand.equals("*"))
result *= x; // multiply
else if (lastCommand.equals("/"))
result /= x; // divide
else if (lastCommand.equals("="))
result = x; // equals
resultLabel.setText("" + result); // display the result to the label
}

//variables
private JLabel resultLabel;
private JPanel panel;
private double result;
private String lastCommand;
private boolean start;
}



  
  
/**
* Define the calculate method
* Perform the calculations on <i>num1</i> and <i>num2</i> depending on
* the operation <i>op</i>
* @param op the operation
* @param num1 the first number of the calculation
* @param num2 the second number of the calculation
* @return the result of the calculation
*/

Hello, I need a help for this section... Could you please resolve it? I need a code. It's java.

Thanks a lot!

Solutions

Expert Solution

/* CalculatorPanel.java */

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

/**
* The calculator panel
* @author
*/
public class CalculatorPanel extends JPanel {
private static final long serialVersionUID = 1L;
private static final int CALC_WIDTH=250;
private static final int CALC_HEIGHT=325;

public CalculatorPanel() {
setLayout(new BorderLayout());
setBackground(Color.lightGray); // create the input/output panel
result = 0; // result variable of label
lastCommand = "=";
start = true;

// add the display
resultLabel = new JLabel("0", SwingConstants.RIGHT); // set the JLabel to RIGHT
resultLabel.setFont(new Font("Helvetica", Font.BOLD, 40)); // set the font size
add(resultLabel, BorderLayout.NORTH); // set the border layout to NORTH
// Action listener creates
ActionListener insert = new InsertAction();
ActionListener command = new CommandAction();

// CREATE A LAYOUT OF THE BUTTONS 4X4 grid
panel = new JPanel();
panel.setLayout(new GridLayout(4, 4)); //set the 4x4 grid
panel.setBackground(Color.DARK_GRAY); //set the background color


// add the button text and assign the action
addButton("7", insert);
addButton("8", insert);
addButton("9", insert);
addButton("/", command);
  
addButton("4", insert);
addButton("5", insert);
addButton("6", insert);
addButton("*", command);
  
addButton("1", insert);
addButton("2", insert);
addButton("3", insert);
addButton("-", command);

addButton("0", insert);
addButton(".", insert);
addButton("=", command);
addButton("+", command);
JButton clear = new JButton("Clear");
clear.setFont(new Font("Helvetica", Font.BOLD, 15)); // set the font size
clear.setForeground(Color.BLUE); //set the font color to blue
clear.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
resultLabel.setText("0");
}
});
add(clear,BorderLayout.SOUTH);
add(panel, BorderLayout.CENTER); // set the panel to center
}
// add button
private void addButton(String label, ActionListener listener) {
JButton button = new JButton(label);
button.setPreferredSize(new Dimension(55,30)); //set the button size
button.setFont(new Font("Helvetica", Font.BOLD, 15)); // set the font size
button.setForeground(Color.BLUE); //set the font color to blue
button.addActionListener(listener); // add the action listener
panel.add(button); // add the button to the panel
}

  
private class InsertAction implements ActionListener {
public void actionPerformed(ActionEvent event) {
String input = event.getActionCommand();
if (start) {
resultLabel.setText("");
start = false;
}   
  
if(!resultLabel.getText().equals("0"))
resultLabel.setText(resultLabel.getText() + input); //display the text to the label when no 0
else{
resultLabel.setText( input); //display the text to the label when 0
}
}
}


private class CommandAction implements ActionListener {
public void actionPerformed(ActionEvent event) {
String command = event.getActionCommand();

if (start) {

if (command.equals("-")) {
resultLabel.setText(command);
start = false;
} else
lastCommand = command;
} else {
calculate(Double.parseDouble(resultLabel.getText()));
lastCommand = command;
start = true;
}
}
}

// method that calculate the result of two inputs
public void calculate(double x) {
if (lastCommand.equals("+"))
result += x; // add
else if (lastCommand.equals("-"))
result -= x; // subtract
else if (lastCommand.equals("*"))
result *= x; // multiply
else if (lastCommand.equals("/"))
result /= x; // divide
else if (lastCommand.equals("="))
result = x; // equals
resultLabel.setText("" + result); // display the result to the label
}

//variables
private JLabel resultLabel;
private JPanel panel;
private double result;
private String lastCommand;
private boolean start;

}

/* CalculatorDriver.java*/


import javax.swing.JFrame;
import javax.swing.*;
import java.awt.event.*;
/*
* Driver Class for the Calcultor
*
* @author
*/
public class CalculatorDriver {
public static void main(String[] args) {
// create JFrame object
JFrame frame=new JFrame("Simple Calculator");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// create object of CalculatorPanel class
CalculatorPanel panel=new CalculatorPanel();
frame.getContentPane().add(panel); // add panel into frame
frame.pack();
frame.setResizable(false); // frame should not be resizable
frame.setLocation(400,300); // set location of frame
frame.setVisible(true); // make frame visible
}
}

/* OUTPUT */

/* PLEASE UPVOTE */


Related Solutions

Python 3 What to fix: When i click the clear button it clears everything but not...
Python 3 What to fix: When i click the clear button it clears everything but not the sold by field import tkinter as tk from tkcalendar import DateEntry from openpyxl import load_workbook window = tk.Tk() window.title("daily logs") # window.resizable(0,0) # labels tk.Label(window, text="Bar code").grid(row=0, sticky="W", pady=20, padx=20) tk.Label(window, text="Products failed").grid(row=1, sticky="W", pady=20, padx=20) tk.Label(window, text="Money Lost").grid(row=2, sticky="W", pady=20, padx=20) tk.Label(window, text="sold by").grid(row=3, sticky="W", pady=20, padx=20) tk.Label(window, text="Failed date").grid(row=4, sticky="W", pady=20, padx=20) # entries barcode = tk.Entry(window) product = tk.Entry(window) money...
Cryptography - please use Python to complete the following task. You don't have to implement AES...
Cryptography - please use Python to complete the following task. You don't have to implement AES just import the necessary libraries. Can you fix my code? Thanks! Read in a 128 bit key from the user (16 characters). If the user enters a key of any other size it's fine to terminate the program with an error. Read in a string of arbitary length from the user. (ie, the string could be 1 character, or 50,000, or anywhere in between)....
(C++ with main to test) 2.2 Task 1 You are going to implement a variant of...
(C++ with main to test) 2.2 Task 1 You are going to implement a variant of the standard linked list, the circular list. The circular linked list is a variant of the standard linked list that wraps around so that traversals through the list will wrap around to the beginning instead of simply reaching the end. This will consist of implementing two classes: cLL and item. 2.2.1 cLL The class is described according to the simple UML diagram below: 2cLL<T>...
C++ (With main to test) 2.2 Task 1 You are going to implement a variant of...
C++ (With main to test) 2.2 Task 1 You are going to implement a variant of the standard linked list, the doubly linked list. Doubly linked lists are because they enable a backwards and forwards traversal of the list through the addition of more pointers. By increasing the memory cost of the list, it enables a better access since the list does not need to be traversed in only one direction. This will consist of implementing two classes: dLL and...
Use Java GUI create following: Task 1: A basic UI with a button and a TextField,...
Use Java GUI create following: Task 1: A basic UI with a button and a TextField, when you press the button, set the button text to the current text field contents. Task 2: set the text field text to the mouse coordinates when that same button is pushed.
1. You can use any materials from the course to complete this task. 2. You are...
1. You can use any materials from the course to complete this task. 2. You are applying for a job and the posting is below: Position: Executive Administrative Assistant at Sinclair Community College. Requires high school diploma or equivalent and some college. Primary duties are customer service, professional writing, research, and basic computer skills. Apply by submitting a cover letter and resume to Natalie Rindler, Human Resource Generalist, 444 West Third Street, Dayton, OH 45402, no later than the posted...
Please answer questions 1-4. You need to show your clear calculation to support each statement provide...
Please answer questions 1-4. You need to show your clear calculation to support each statement provide a paragraph of interpretation related to the result of your analysis on each statement. I can't award credit if all questions and instructions are not answered. Question 1: Common size for income statement Income Statement (Common Size) :                                                                  Consolidated Income Statement 2011 % 2010 % Revenue $19,176.1 $18,627.0    Cost of sales ( 10,571.7) ( 10,239.6 ) Gross Profit      8,604.4     8,387.4...
How would you implement the plan and /or launch a compensation change? Provide a clear and...
How would you implement the plan and /or launch a compensation change? Provide a clear and effective roll out plan for the program (whether new and /or if you recommend changes) as well as possible methods to assess the effectiveness.
Instructions:: You need to show your clear calculation to support each statement provide a paragraph of...
Instructions:: You need to show your clear calculation to support each statement provide a paragraph of interpretation related to the result of your analysis on each statement. Question 1: Common size for income statement Income Statement (Common Size) :                                                                  Consolidated Income Statement 2011 % 2010 % Revenue $19,176.1 $18,627.0    Cost of sales ( 10,571.7) ( 10,239.6 ) Gross Profit      8,604.4     8,387.4 Selling and administrative expenses (   6,149.6) ( 5,953.7) Restructuring charges (      195.0)       0.0 Goodwill...
Project #1 Designing and implementing the Game of Life The main task is to implement (in...
Project #1 Designing and implementing the Game of Life The main task is to implement (in java) a 2-D (or 3-D) Graphic version of the Game of Life
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT