import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.text.DecimalFormat; public class CarGUI extends JFrame implements ActionListener { private Car car; private DecimalFormat format = new DecimalFormat("######.0###"); // GUI components private JLabel lblDrive = null; private JLabel lblInTank = null; private JTextField txtDrive = null; private JButton btnDrive = null; private JButton btnFill = null; /** * Answers a GUI for the Car object * @param Car c the Car object **/ public CarGUI(Car c) { super(c.getCarName()); car = c; // init gui stuff lblDrive = new JLabel("Miles to Drive: "); lblInTank = new JLabel("Left in Tank: " + car.getFuelInTank()); txtDrive = new JTextField(5); btnDrive = new JButton("Drive"); btnFill = new JButton("Fill Up"); setupLayout(); setDefaultCloseOperation(EXIT_ON_CLOSE); } /** * Encapsulates the layout of the GUI **/ public void setupLayout() { Container c = getContentPane(); c.setLayout(new FlowLayout()); c.add(lblDrive); c.add(txtDrive); c.add(btnDrive); c.add(btnFill); c.add(lblInTank); btnDrive.addActionListener(this); btnFill.addActionListener(this); setSize(250, 100); setLocation(100, 100); setVisible(true); } /** * Responds to button clicks * @param ActionEvent e the event (button click) * **/ public void actionPerformed(ActionEvent e) { if (e.getSource() == btnDrive) { if (txtDrive.getText().trim().compareTo("") != 0){ double d = Double.parseDouble( txtDrive.getText()); car.drive(d); lblInTank.setText("Left in Tank: " + format.format(car.getFuelInTank())); txtDrive.setText(""); } } else if(e.getSource() == btnFill) { car.fillTank(); lblInTank.setText("Left in Tank: " + car.getFuelInTank()); } } public static void main(String args[]) { CarGUI cg1 = new CarGUI(new Car("Ford Mustang")); CarGUI cg2 = new CarGUI(new Car("Honda Accord", 35, 12)); } }