Component Type Purpose txtNum JTextField Input for number of tickets chkMatinee
ID: 2246654 • Letter: C
Question
Component
Type
Purpose
txtNum
JTextField
Input for number of tickets
chkMatinee
JCheckBox
Check if matinee performance
radOrchestra
JRadioButton
Check for orchestra tickets
radMezzanine
JRadioButton
Check for mezzanine tickets
radBalcony
JRadioButton
Check for balcony tickets
btnCalc
JButton
Click to calculate price
txtEach
JTextField
Displays price of each ticket
txtTotal
JTextField
Displays total price
Clicking the CalcPrice button should determine the price per ticket and the total price based on the user’s input and display in txtEach and txtTotal. You should make sure the number of tickets is entered and a ticket type is selected, otherwise give an error message.
The action listener for btnCalc is set up as follows.
btnCalc.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
calcPrice(); //write the code for this method
}
});
Write the calcPrice method that is called by the action listener. This class method has access to all of the GUI components. You DO NOT HAVE TO CODE THE GUI. ONLY write the code for this method which does all the work. The header for the method is:
private void calcPrice()
Component
Type
Purpose
txtNum
JTextField
Input for number of tickets
chkMatinee
JCheckBox
Check if matinee performance
radOrchestra
JRadioButton
Check for orchestra tickets
radMezzanine
JRadioButton
Check for mezzanine tickets
radBalcony
JRadioButton
Check for balcony tickets
btnCalc
JButton
Click to calculate price
txtEach
JTextField
Displays price of each ticket
txtTotal
JTextField
Displays total price
Explanation / Answer
PROGRAM CODE:
public void calcPrice()
{
//prices of each ticket
final double Orchestra = 85, Mezzanine = 70, Balcony = 45;
double price = 0;
//checking if a ticket is selected or not
if((!radBalcony.isSelected() && !radMezzanine.isSelected() && !radOrchestra.isSelected()))
System.out.println("Please select a ticket");
//checking if the number of tickets is entered
else if (txtNum.equals(""))
System.out.println("Please enter the number of tickets");
else
{
//Balcony ticket
if(radBalcony.isSelected())
{
price = Integer.valueOf(txtNum.getText()) * Balcony;
txtEach.setText("$" + Balcony);
}
//Mezzanine Ticket
else if(radMezzanine.isSelected())
{
price = Integer.valueOf(txtNum.getText()) * Mezzanine;
txtEach.setText("$" + Mezzanine);
}
//Orchestra ticket
else
{
price = Integer.valueOf(txtNum.getText()) * Orchestra;
txtEach.setText("$" + Orchestra);
}
//In case of Matinee performance - 15% discount
if(chkMatinee.isSelected())
price -= price*0.15;
//Settng final price
txtTotal.setText("$" + price);
}
}
The above function will update the fields txtEach and txtTotal depending on the ticket selection.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.