Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Write an application or applet that implements a trip-time calculator. Define and use a class TripComputer to compute the time of a trip. TripComputer should

Write an application or applet that implements a trip-time calculator. Define and use a class TripComputer to compute the time of a trip. TripComputer should have the private attributes totalTimethe total time for the trip restStopTakena boolean flag that indicates whether a rest stop has been taken at the end of the current leg and the following methods: computeLegTime(distance, speed)computes the time for a leg of the trip having a given distance in miles and speed in miles per hour. If either the distance or the speed is negative, throws an exception. T akeRestStop(time)takes a rest stop for the given amount of time. If the time is negative, throws an exception. Also throws an exception if the client code attempts to take two rest stops in a row. getTripTimereturns the current total time for the trip. Here is one possible configuration of the labels, buttons, and text fields required by the trip-time calculator:

Trip Computer

- totalTime: double

- restStopTaken: boolean

+TripComputer()

+computerLegTime(double distance, double speed):void throws TripComputerException

+takeRestStop(double time): void throws TripComputerException

+getTripTime(): double

1. Constructor: set totalTime to zero and restStopTaken to true

2. computerLegTime()

a. If distance or speed are less than equal to zero, throw exception

b. Calculate legTime as distance / speed

c. Add legTime to totalTime

d. Set restStopTaken to false

3. takeRestStop()

a. if time is less than equal to zero, throw exception

b. if restStopTaken is true throw exception

c. add time to totalTime

d. set restStopTaken to true

extra class if needed:

public class TripComputerException extends Exception{

/** * Creates a new instance of TripComputerException */ public TripComputerException(String reason) { super(reason); }

}

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

public class TripComputerApplication extends JFrame implements ActionListener { public static final int WIDTH = 500; public static final int HEIGHT = 200;

private TripComputer theComputer;

public JLabel totalTimeLabel; public JTextField distanceTextField; public JTextField speedTextField; public JTextField timeTextField;

/** * Creates a new instance of TripComputerApplication */ public TripComputerApplication() { setTitle("Trip Time Computer"); setSize(WIDTH, HEIGHT); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

Container contentPane = getContentPane(); contentPane.setBackground(Color.GREEN); contentPane.setLayout(new BorderLayout());

// Do the panel for the rest stop timeTextField = new JTextField(); JLabel timeLabel = new JLabel("Stop Time (hours)");

JButton stopButton = new JButton("Add Stop"); stopButton.addActionListener(this);

JPanel stopPanel = new JPanel(); stopPanel.setLayout(new GridLayout(3, 1, 30, 0));

stopPanel.add(timeTextField); stopPanel.add(timeLabel); stopPanel.add(stopButton);

contentPane.add(stopPanel, BorderLayout.WEST);

// Do the panel for the leg distanceTextField = new JTextField(); JLabel distanceLabel = new JLabel("Distance (miles)");

speedTextField = new JTextField(); JLabel speedLabel = new JLabel("Speed (mph)");

JButton legButton = new JButton("Add Leg"); legButton.addActionListener(this);

JPanel legPanel = new JPanel(); legPanel.setLayout(new GridLayout(5, 1, 30, 0));

legPanel.add(distanceTextField); legPanel.add(distanceLabel); legPanel.add(speedTextField); legPanel.add(speedLabel); legPanel.add(legButton);

contentPane.add(legPanel, BorderLayout.EAST);

totalTimeLabel = new JLabel("Your trip time so far (hours): ");

contentPane.add(totalTimeLabel, BorderLayout.SOUTH);

theComputer = new TripComputer(); }

public void actionPerformed(ActionEvent e) { String actionCommand = e.getActionCommand(); Container contentPane = getContentPane(); if (actionCommand.equals("Add Leg")){ try{ double speed = Double.parseDouble(speedTextField.getText().trim()); double distance = Double.parseDouble(distanceTextField.getText().trim()); theComputer.computeLegTime(distance, speed); totalTimeLabel.setText("Your trip time so far (hours): " + theComputer.getTripTime()); } catch(TripComputerException ex){ totalTimeLabel.setText("Error: " + ex.getMessage()); } catch(Exception ex){ totalTimeLabel.setText("Error in speed or distance: " + ex.getMessage()); } } else if (actionCommand.equals("Add Stop")){ try{ double time = Double.parseDouble(timeTextField.getText().trim()); theComputer.takeRestStop(time); totalTimeLabel.setText("Your trip time so far (hours): " + theComputer.getTripTime()); } catch(TripComputerException ex){ totalTimeLabel.setText("Error: " + ex.getMessage()); } catch(Exception ex){ totalTimeLabel.setText("Error in time: " + ex.getMessage()); } } else System.out.println("Error in button interface."); }

public static void main(String[] args) { TripComputerApplication gui = new TripComputerApplication(); gui.setVisible(true); } }

Part 2: Write an application or applet that implements a simple text editor. Use a text field and a button to get the file. Read the entire file as characters and display it in a JTextArea. The user will then be able to make changes in the text area. Use a Save button to get the contents of the text area and write that over the original file. Technical Details: Read each line from the file and then display the line in the text area using the method append(aString). The method getText will return all of the text in the text area in a string that then can be written to the file. The following statement will make the text area referenced by editorTextArea scrollable: JScrollPane scrollPane = new JScrollPane(editorTextArea); Then add scrollPane to your GUI, just as you would any other component. The text area editorTextArea does not need to be added to the GUI, but it can be used. Use the contacts.txt file provided.

contacts.txt:

bob# 555-1212# # # bob@funky.com# fred# # 333-3456# # # Lover's Lane susan# # # 555-2135# # easy street 

Simple Editor extends JFrame implements ActionListener

-WIDTH: static final int

-HEIGHT: static final int

-NUM_OF_CHAR: static final int

-filename: String

-fileNameLabel: JLabel

-reportLabel: JLabel

-fileNameField: JTextField

-fileButton: JButton

-saveButton: JButton

-editorTextArea: JTextArea

-scrollPane: JScrollPane

-filePanel: JPanel

+main()

+SimpleEditor()

+actionPerformed(ActionEvent e)

+getFile()

+saveFile()

1. Main method will do the following:

a. Call the SimpleEditor constructor

b. Make the object visible

2. SimpleEditor constructor

a. setSize

b. setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_CLOSE);//This is the exact code for this

c. Create a container named contentPane

d. Set layout to BorderLayout

e. Set Layout of filePanel to FlowLayout

f. Add filePanel to content pane, in the NORTH

g. Add fileNameLabel, fileNameField, fileButton and reportLabel to the filePanel

h. Add actionListener to fileButton

i. Add scrollPane to content pane, in the CENTER

j. Add actionListener to saveButton

k. Add saveButton to content pane, in the SOUTH

3. getFile()

a. Retrieve the file from the filenameField and store it in filename

b. Create an instance of File give filename

c. Set the editorTextArea to empty

d. Check to see if the file exists

i. If the file does not exist, setText of reportLabel to New file: Start editing it.

ii. If the file exists but cant be read, setText of reportLabel to That file is not readable.);

iii. Otherwise, try reading the file

iv. While line read is not null

1. Append line read to the editorTextArea

2. Read in next line

v. Close your file

vi. Catch IOException

1. setText of reportLabel to Problem reading from file

4. saveFile()

a. Retrieve text from editorTextArea

b. Create a new File

c. Try

i. Create a new outputFile

ii. Write the content from editorTextArea to the output file

iii. Set the text of reportLabel to File was written

iv. Close the file

d. Catch

i. Set the text of reportLabel to Problem writing the file

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Databases On The Web Designing And Programming For Network Access

Authors: Patricia Ju

1st Edition

1558515100, 978-1558515109

More Books

Students also viewed these Databases questions

Question

Discuss the elements of socialization.

Answered: 1 week ago