A jtextfield which contains a whole number

This preview shows page 11 - 14 out of 23 pages.

a JTextField which contains a whole number representing the number of kilometres priceB – a JButton displaying the String, “PRICE”. priceT a JTextField which displays, in dollars and cents, the cost of travelling the stated number of kilometres Below is a screenshot of the JPanel when it is first displayed. The centsPerKT JTextField displays “ 12 ”, the numberKT JTextField displays “ 100 ” and the priceT JTextField displays $12.0 ”. In the centsPerKT JTextField, the user enters a whole number, representing the cost in cents of travelling one kilometre. In the numberKT JTextField, the user enters a whole number, representing the number of kilometres. When the user presses the PRICE JButton, the cost of travelling the stated number of kilometres at the stated cost in cents per kilometre is displayed, in dollars and cents, in the priceT JTextField. You are required to complete the JPanel definition on the next page so that the JPanel behaves as described above. You must use the variables given in the code. The screenshots below show the JPanel after the user has pressed the PRICE JButton.
Image of page 11

Subscribe to view the full document.

- 12 - COMPSCI 101 Question/Answer Sheet ID: ..................................................................... CONTINUED import java.awt.*; import java.awt.event.*; import javax.swing.*; public class AJPanel extends JPanel implements ActionListener { private JTextField numberKT, centsPerKT, priceT; private JButton priceB; public AJPanel() { JLabel numberKL = new JLabel("Kilometres"); JLabel centsPerKL = new JLabel("Cents per kilometre"); numberKT = new JTextField(4); centsPerKT = new JTextField(4); priceT = new JTextField(12); priceB = new JButton("PRICE"); priceB.addActionListener(this); centsPerKT.setText("12"); numberKT.setText("100"); priceT.setText("$12.0"); add(centsPerKL); add(centsPerKT); add(numberKL); add(numberKT); add(priceB); add(priceT); } public void actionPerformed ( ActionEvent e) { int centsPerK = Integer.parseInt(centsPerKT.getText()); int ks = Integer.parseInt(numberKT.getText()); double cost = centsPerK * ks / 100.0; priceT.setText("$" + cost); } } (11 marks)
Image of page 12