I am making a simple program the user enters in a number using JButtons 0-9 and then the user clicks gallons or miles to add the number to one or the other. Here is my code:
import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.*; public class SouthPanel extends JPanel{ JLabel milesTitle, fuelTitle, saveTitle, milesText, fuelText, saveText, topLabel; JButton miles, gallons, save; public SouthPanel (JLabel northLabel){ topLabel = northLabel; milesTitle = new JLabel("total miles"); fuelTitle = new JLabel("fuel consumed"); saveTitle = new JLabel("save to file"); milesText = new JLabel("0.0"); fuelText = new JLabel("0.0"); saveText = new JLabel("\"statistics.txt\""); JButton miles = new JButton("miles"); JButton gallons = new JButton("gallons"); JButton save = new JButton("Save"); ButtonListener listener = new ButtonListener(); miles.addActionListener(listener); gallons.addActionListener(listener); save.addActionListener(listener); setLayout(new GridLayout(3,3)); add(milesTitle); add(milesText); add(miles); add(fuelTitle); add(fuelText); add(gallons); add(saveTitle); add(saveText); add(save); } private class ButtonListener implements ActionListener{ public void actionPerformed (ActionEvent event){ double temp = 0; double temp2 = 0; double sumit = 0; if (event.getSource() == miles){ temp = Double.parseDouble(topLabel.getText()); temp2 = Double.parseDouble(milesText.getText()); sumit = temp + temp2; milesText.setText("" + sumit); topLabel.setText(""); } if (event.getSource() == gallons){ temp = Double.parseDouble(topLabel.getText()); temp2 = Double.parseDouble(fuelText.getText()); sumit = temp + temp2; fuelText.setText("" +sumit); topLabel.setText(""); } } } }
It runs and compiles fine, but my two button listeners dont seem to be working. When i click one of them nothing happens. Is there something wrong with-in the code of each button?