Distance convertor issue - java

I can't obtain exact conversion due to unknown logical error. The program has three input fields. Where the user inputs desired value in desired field. Based on the entry and field of entry the data is converted.
package dist;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
#SuppressWarnings("serial")
public class DistanceConvertor extends JFrame
{
private JLabel KilometreLabel;
private JLabel MilesLabel;
private JLabel NauticalMilesLabel;
private JTextField KilometreTF;
private JTextField MilesTF;
private JTextField NauticalMilesTF;
private kiloHandler KilometreHandler;
private nauticalHandler NauticalMilesHandler;
private milesHandler MilesHandler;
private static final int WIDTH = 400;
private static final int HEIGHT = 100;
private static final double OFFSET = 0.0621;
private static final double OFFSET1 = 0.5399568;
public DistanceConvertor()
{
setTitle("Distance Convertor");
Container c = getContentPane();
c.setLayout(new GridLayout(3,4));
KilometreLabel = new JLabel("Distance in Kilometre:\n ",
SwingConstants.RIGHT);
MilesLabel = new JLabel("Distance in Miles: ",
SwingConstants.RIGHT);
NauticalMilesLabel = new JLabel("Distance in Nautical Miles: ",
SwingConstants.RIGHT);
KilometreTF = new JTextField(7);
MilesTF = new JTextField(7);
NauticalMilesTF = new JTextField(7);
c.add(KilometreLabel);
c.add(KilometreTF);
c.add(MilesLabel);
c.add(MilesTF);
c.add(NauticalMilesLabel);
c.add(NauticalMilesTF);
KilometreHandler = new kiloHandler();
MilesHandler = new milesHandler();
NauticalMilesHandler=new nauticalHandler();
KilometreTF.addActionListener(KilometreHandler);
MilesTF.addActionListener(MilesHandler);
NauticalMilesTF.addActionListener(NauticalMilesHandler);
setSize (WIDTH, HEIGHT);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
private class kiloHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double kilometre, miles,nauticalmiles;
kilometre =
Double.parseDouble(KilometreTF.getText());
nauticalmiles =
Double.parseDouble(NauticalMilesTF.getText());
miles = kilometre * OFFSET;
MilesTF.setText(String.format("%.4f", miles));
}
}
private class milesHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double kilometres, miles;
miles =
Double.parseDouble(MilesTF.getText());
kilometres = (miles / OFFSET) ;
KilometreTF.setText(String.format("%.4f", kilometres));
}
}
private class nauticalHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
double kilometres, miles,nauticalmiles;
kilometres =
Double.parseDouble(KilometreTF.getText());
nauticalmiles= (kilometres / OFFSET1) ;
NauticalMilesTF.setText(String.format("%.4f", nauticalmiles));
}
}
public static void main(String[] args)
{
DistanceConvertor DistConv = new DistanceConvertor();
DistConv.setLocationRelativeTo(null);
}
}
When I enter any value in any of the three fields I want to get conversion value. But due to some error I don't get the converted value.

Related

Why does inherited methods only work for one class?

I am new to Java and programming in general and also new to Stack overflow. Im taking a course in object orientation and i am stuck at one assignment. Hope i can get some tips or feedback here.
I have written a fictive Banking program and now i am supposed to write an user interface.
The class SubMenuWindow have graphic components to draw a window in whitch i want to show all my Customers names and ID-numbers.
The Classes CustomerSubWindow and CreditAccountSubWindow inherits from SubMenuWindow since i want both of them to display the customers names and ID numbers.
When i create customer objects everthing works as its supossed to in the frame created from CustomerSubWindow, but the Frame created from CreditAccountWindow wont display the names and ID-numbers. Both inherit from the same parentclass, why dont they have the same behaviour?
I have tried to rewrite the code in different ways but the error persists. Can someone see what might be wrong?
I am aware that there are a bunch of formal convention errors (indentation, varabel names etc)
Here are the three classes:
First is the parent class:
public abstract class SubMenuWindow extends JFrame {
protected BankLogic bank = new BankLogic();
private JPanel customersDisplayPanel;
private JLabel customersDisplayLabel;
JTextArea customersDisplayText;
private GridBagLayout gridBag;
private GridBagConstraints customGrid;
private FlowLayout layout;
private JScrollPane scrollBarDisplayText;
private static final int TEXT_LENGTH = 30;
private static final int ROWS = 20;
private static final int COLUMNS = 50;
private static final int FRAME_HEIGHT = 900;
private static final int FRAME_WIDTH = 1600;
public SubMenuWindow(String title) {
super(title);
createComponents();
FlowLayout layout = new FlowLayout();
this.setSize(FRAME_WIDTH, FRAME_HEIGHT);
this.setVisible(false);
this.setDefaultCloseOperation(HIDE_ON_CLOSE);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setLayout(layout);//
this.add(customersDisplayPanel);
}
private void createComponents(){
gridBag = new GridBagLayout();
customGrid = new GridBagConstraints();
customersDisplayPanel = new JPanel(gridBag);
customersDisplayLabel = new JLabel("Within this frame you can find all
the Customers in the bank");
setCustomersDisplayText(new JTextArea(ROWS,COLUMNS));
scrollBarDisplayText = new JScrollPane(getCustomersDisplayText());
customGrid.gridx = 0;
customGrid.gridy = 1;
customersDisplayPanel.add(customersDisplayLabel, customGrid);
customGrid.gridx = 0;
customGrid.gridy = 2;
customersDisplayPanel.add(scrollBarDisplayText,customGrid);
}
public void createBankLogicCustomer(String firstNameString, String
surNameString, String pnumString ){
bank.createCustomer(firstNameString, surNameString, pnumString);
updateCustomersTextArea();
}
public void updateCustomersTextArea(){
customersDisplayText.setText("");
for(String customer : bank.getAllCustomers()){
customersDisplayText.append(customer + "\n");
}
}
public BankLogic getBank(){
return bank;
}
public static int getTextLength() {
return TEXT_LENGTH;
}
public JTextArea getCustomersDisplayText() {
return customersDisplayText;
}
public void setCustomersDisplayText(JTextArea customersDisplayText) {
this.customersDisplayText = customersDisplayText;
}
}
Second class
public class CustomerSubWindow extends SubMenuWindow {
private JPanel nameInputPanel;
private JTextField firstNameTextField;
private JTextField surNameTextField;
private JTextField pNumTextField;
private JLabel firstNameLabel;
private JLabel surNameLabel;
private JLabel pNumLabel;
private JButton finishButton;
private ActionListener createCustomerButtonPressed;
public CustomerSubWindow(String title) {
super(title);
createComponents();
this.add(nameInputPanel);
}
public void createComponents(){
nameInputPanel = new JPanel();
firstNameTextField = new JTextField(super.getTextLength());
surNameTextField= new JTextField(super.getTextLength());
pNumTextField= new JTextField(super.getTextLength());
firstNameLabel= new JLabel("First name: ");
surNameLabel= new JLabel("Surname: ");
pNumLabel= new JLabel("Person number: ");
finishButton = new JButton("Create customer");
createCustomerButtonPressed = new CustomerButtonListener();
finishButton.addActionListener(createCustomerButtonPressed);
nameInputPanel.add(firstNameLabel);
nameInputPanel.add(firstNameTextField);
nameInputPanel.add(surNameLabel);
nameInputPanel.add(surNameTextField);
nameInputPanel.add(pNumLabel);
nameInputPanel.add(pNumTextField);
nameInputPanel.add(finishButton);
}
private class CustomerButtonListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent custButtonPressed){
if (custButtonPressed.getSource()==finishButton){
String firstNameString = firstNameTextField.getText();
String surNameString = surNameTextField.getText();
String pnumString = pNumTextField.getText();
createBankLogicCustomer(firstNameString, surNameString,
pnumString);
updateCustomersTextArea();
}
}
}
}
And finally the third Class
public class CreditAccountSubWindow extends SubMenuWindow {
private JPanel pNoInputPanel;
private JTextField pNoTextField;
private JLabel pNoLabel;
private JButton pNoButton;
private ActionListener createCreditAccountButtonPressed;
public CreditAccountSubWindow(String title)
super(title);
createComponents();
this.add(pNoInputPanel);
}
public void createComponents(){
pNoInputPanel = new JPanel();
pNoTextField = new JTextField(super.getTextLength());
pNoLabel = new JLabel("Input client ID number");
pNoButton = new JButton("Create Account");
createCreditAccountButtonPressed = new CreditAccButtonListener();
pNoButton.addActionListener(createCreditAccountButtonPressed);
pNoInputPanel.add(pNoLabel);
pNoInputPanel.add(pNoTextField);
pNoInputPanel.add(pNoButton);
}
private class CreditAccButtonListener implements ActionListener{
#Override
public void actionPerformed(ActionEvent creditAccButtonPressed){
if (creditAccButtonPressed.getSource()==pNoButton){
String pNo = pNoTextField.getText();
getBank().createCreditAccount(pNo);
System.out.println(getBank().createCreditAccount(pNo));
}
}
}
}

how to make these 2 files into a funtional program

My professor told me to put both of these together to make a running program. I am utilizing Netbeans, and it keeps telling me that there is no main class. Am I supposed to create one or am I missing something? How do I put these together into a working gui java application?
Here is the first file, it is called NumberGame
import java.util.Random;
public class NumberGame {
private Random rand = new Random();
private int min, max;
private int num1, num2;
public NumberGame(int min, int max) {
this.min = min;
this.max = max;
newNums();
}
public int getNum1() {
return num1;
}
public int getNum2() {
return num2;
}
public void newNums() {
num1 = rand.nextInt(max - min + 1) + min;
num2 = rand.nextInt(max - min + 1) + min;
}
public int calcSum() {
return num1 + num2;
}
public boolean checkSum(int num) {
return num == calcSum();
}
}
The second file is called App here it is
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class App extends JFrame implements ActionListener {
/* Canvas ============================================ */
private NumberGame numbers;
private Font mainFont = new Font(Font.SANS_SERIF, Font.PLAIN,16);
/* Components for Canvas ============================= */
private JTextField messageField;
private JLabel lblNum1;
private JLabel lblNum2;
private JTextField sumField;
private JButton btnNext;
private JButton btnCheck;
public App(String title, int width, int height) {
// initialize new number game
numbers = new NumberGame(10, 49);
// initialize components
messageField = new JTextField("", 10);
messageField.setEditable(false);
messageField.setHorizontalAlignment(JTextField.CENTER);
messageField.setFont(mainFont);
// add components to board
add(messageField, BorderLayout.NORTH);
add(createCenter(), BorderLayout.CENTER);
add(createButtonPanel(), BorderLayout.SOUTH);
// add action listeners
btnCheck.addActionListener(this);
btnNext.addActionListener(this);
sumField.addActionListener(this);
// create the window
createWindow(title, width, height);
pack();
}
private void createWindow(String title, int width, int height) {
setVisible(true);
setTitle(title);
setSize(width, height);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private JPanel createCenter() {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(3, 2));
JLabel lblNumPrompt1 = new JLabel("Number 1 = ", JLabel.RIGHT);
lblNumPrompt1.setFont(mainFont);
lblNum1 = new JLabel(Integer.toString(numbers.getNum1()), JLabel.CENTER);
lblNum1.setFont(mainFont);
JLabel lblNumPrompt2 = new JLabel("Number 2 = ", JLabel.RIGHT);
lblNumPrompt2.setFont(mainFont);
lblNum2 = new JLabel(Integer.toString(numbers.getNum2()), JLabel.CENTER);
lblNum2.setFont(mainFont);
JLabel lblSumPrompt = new JLabel("Sum = ", JLabel.RIGHT);
lblSumPrompt.setFont(mainFont);
sumField = new JTextField("0", 10);
sumField.setHorizontalAlignment(JTextField.CENTER);
sumField.setFont(mainFont);
// add objects to the panel
panel.add(lblNumPrompt1);
panel.add(lblNum1);
panel.add(lblNumPrompt2);
panel.add(lblNum2);
panel.add(lblSumPrompt);
panel.add(sumField);
return panel;
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel();
btnNext = new JButton("Next");
btnCheck = new JButton("Check");
panel.add(btnNext);
panel.add(btnCheck);
return panel;
}
#Override
public void actionPerformed(ActionEvent e) {
JButton button = (JButton) e.getSource();
if (button.equals(btnNext)) {
numbers.newNums();
lblNum1.setText(Integer.toString(numbers.getNum1()));
lblNum2.setText(Integer.toString(numbers.getNum2()));
} else {
int num = Integer.parseInt(sumField.getText());
if (numbers.checkSum(num))
messageField.setText("Correct!");
else
messageField.setText("Try Again!");
}
}
}
Simply create a main class and initialize the app class as below, HTH.
public static void main(String args[])
{
//Put in the title and size of the Panel
App app1 = new App("MY game", 1000, 900);
}
Create a main class .
Put all 3 classes into same package.
Simply create an object of App class in main class.
Run the main class.

What causes "Number format exception / empty string" error in the following code?

I am trying to write a GUI temperature converter. It has one JTextField and two JButtons. TextField accepts the temperature which the user wants to convert and the user presses the appropriate button. Whenever I click on anyone of the buttons, I get a "Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: empty String" error. Please Help!
public class tempcon extends JFrame {
private JPanel panel;
private JLabel messageLabel;
public JTextField tempC;
private JButton calcButton, calcButton1;
private final int WINDOW_WIDTH = 300;
private final int WINDOW_HEIGHT = 140;
public tempcon() {
setTitle("Temperature convertion");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildPanel();
add(panel);
setVisible(true);
}
public double getTempC(){
return Double.parseDouble(tempC.getText());
}
private void buildPanel() {
tempC = new JTextField(10);
messageLabel = new JLabel("Enter tempurture");
calcButton = new JButton("Convert to Fahrenheit");
calcButton1 = new JButton("Convert to Celcius");
calcButton.addActionListener(new CalcButtonListener());
calcButton1.addActionListener(new CalcButtonListener1());
panel = new JPanel();
panel.add(messageLabel);
panel.add(tempC);
panel.add(calcButton);
panel.add(calcButton1);
}
public static void main(String[] args){
new tempcon().buildPanel();
}
}
class CalcButtonListener1 implements ActionListener {
public void actionPerformed(ActionEvent e) {
double input;
double temp;
input = new tempcon().getTempC();
temp = input * 1.8 + 32;
JOptionPane.showMessageDialog(null, "That is " + temp + "
degrees Celsius.");
}
}
class CalcButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
double input;
double temp;
input = new tempcon().getTempC();
temp = (input - 32)*1.8;
JOptionPane.showMessageDialog(null, "That is " + temp + "
degrees Fehrenheit.");
}
public static void main(String[] args) {
tempcon myTempWindowInstance = new tempcon();
}
}
The problem is that you are recreating a new frame in your action listeners : new tempcon().getTempC() .
The textfields in these new frames are obviously empty and you get your error.
Consider referring to the same instance of tempcon everywhere, that is simply replace
new tempcon().getTempC();
with
getTempC();
, which will call the getTempC() method of the outer tempcon instance .

I am getting a Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "Years:"

This is one code file (i think this is where the error is but i might be mistaken) the run time error mentions "years: " which is located in this file. here is the full error. Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "Years:"
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
/**
A frame that shows the growth of an investment with variable interest,
using a bar chart.
*/
public class InvestmentFrame4 extends JFrame
{
private static final int FRAME_WIDTH = 400;
private static final int FRAME_HEIGHT = 400;
private static final int CHART_WIDTH = 300;
private static final int CHART_HEIGHT = 300;
private static final double DEFAULT_RATE = 5;
private static final double INITIAL_BALANCE = 1000;
private JLabel rateLabelInitialInvestment;
private JLabel rateLabelInterestRate;
private JLabel rateLabelYears;
private JTextField rateFieldInitialInvestment;
private JTextField rateFieldInterestRate;
private JTextField rateFieldYears;
private JButton button;
private ChartComponent chart;
private double balance;
public InvestmentFrame4()
{
// balance = Double.parseDouble(rateLabelInitialInvestment.getText());
chart = new ChartComponent(3 * INITIAL_BALANCE);
chart.setPreferredSize(new Dimension(CHART_WIDTH, CHART_HEIGHT));
chart.append(INITIAL_BALANCE);
createInterestRateTextField();
createInitialInvestmentTextField();
createYearsTextField();
createButton();
createPanel();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
private void createInterestRateTextField()
{
rateLabelInterestRate = new JLabel("Interest Rate: ");
final int FIELD_WIDTH = 25;
rateFieldInterestRate = new JTextField(FIELD_WIDTH);
rateFieldInterestRate.setText("" + DEFAULT_RATE);
}
private void createInitialInvestmentTextField()
{
rateLabelInitialInvestment = new JLabel("Initial Investment: ");
final int FIELD_WIDTH = 20;
rateFieldInitialInvestment = new JTextField(FIELD_WIDTH);
rateFieldInitialInvestment.setText("" + DEFAULT_RATE);
}
private void createYearsTextField()
{
rateLabelYears = new JLabel("Years: ");
final int FIELD_WIDTH = 20;
rateFieldYears = new JTextField(FIELD_WIDTH);
rateFieldYears.setText("" + DEFAULT_RATE);
}
class AddInterestListener implements ActionListener
{
public void actionPerformed(ActionEvent event)
{
for(int i = 1; i < Integer.parseInt(rateLabelYears.getText().trim()); i++)
{
balance = Double.parseDouble(rateLabelInitialInvestment.getText()) * Math.pow(1.0 + Double.parseDouble(rateLabelInterestRate.getText()), Integer.parseInt(rateFieldYears.getText()));
}
}
}
private void createButton()
{
button = new JButton("Compound Interest");
ActionListener listener = new AddInterestListener();
button.addActionListener(listener);
}
private void createPanel()
{
JPanel panel = new JPanel();
panel.add(rateLabelInitialInvestment);
panel.add(rateFieldInitialInvestment);
panel.add(rateLabelInterestRate);
panel.add(rateFieldInterestRate);
panel.add(rateLabelYears);
panel.add(rateFieldYears);
panel.add(button);
panel.add(chart);
add(panel);
}
}
Here is another file
public class ChartComponent extends JComponent
{
private ArrayList<Double> values;
private double maxValue;
public ChartComponent(double max)
{
values = new ArrayList<Double>();
maxValue = max;
}
public void append(double value)
{
values.add(value);
repaint();
}
public void paintComponent(Graphics g)
{
final int GAP = 5;
final int BAR_HEIGHT = 10;
int y = GAP;
for (double value : values)
{
int barWidth = (int) (getWidth() * value / maxValue);
g.fillRect(0, y, barWidth, BAR_HEIGHT);
y = y + BAR_HEIGHT + GAP;
}
}
}
and finally the main
import javax.swing.JFrame;
/**
This program displays the growth of an investment, showing
a bar chart.
*/
public class InvestmentViewer4
{
public static void main(String[] args)
{
JFrame frame = new InvestmentFrame4();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
if someone could please explain i am getting the run time error it would be greatly appreciated!!!!
the problem occurs here:
for(int i = 1; i < Integer.parseInt(rateLabelYears.getText().trim()); i++)
rateLabelYears is a JLabel, that will always have the text of "years" unless you change it otherwise. You've mistaken it with the rateFieldYears which is an identifier to the JTextField that takes input for the years.
you'll need this:
for(int i = 1; i < Integer.parseInt(rateFieldYears.getText().trim()); i++){
...
...
...
}

ArrayList prints out a code from gui

I am having some serious trouble.
My program that I have to write is a GUI that essentially asks for:
A Course (ex: cpsc130)
The name (ex: computer programming 2)
The amount of credits you receive for the class (ex 3)
And your grade (ex A, B).
I'm not very good with ActionListeners, escentially I have no idea what I'm doing with it. I have to make an ArrayList for the information
One ArrayList<Course> (instance variable) e.g. courseList, to store the courses you add;
Four inner ActionListener classes, with each of them implements its method of
actionPerformed. Specically,
AddCourseListener: read the inputs and create a course object, add the course
object into the courseList, and append this into the output area;
CalGPAListener: read all course credits and grades from the courseList, add
them up and compute the overall GPA. You are assuming that A is 4, B is 3, C is 2,
D is 1, and E is 0. GPA = Sum(creditpoint)=totalCredits. For instance (Figure
1), you have taken 3 courses: 130 (3 credits, grade of A), 131 ( 3 credits, grade of
B), and 370 (4 credits, grade of B), then your GPA = (3*4+3*3+4*3)/(3+3+4)
= 3.3.
ResetInputListener: reset all input elds;
ResetOutputListener: reset output area.
Those are all the ActionListeners I need. I will show you my code so far. When compiled it will show all the Buttons and TextAreas, the ActionListeners are the only thing I need help with.
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
public class DegreeWorksFrame extends JFrame {
private JLabel courseCodeLabel;
private JTextField courseCodeField;
private JLabel courseNameLabel;
private JTextField courseNameField;
private JLabel courseCreditLabel;
private JTextField courseCreditField;
private JLabel courseGradeLabel;
private JTextField courseGradeField;
private JTextArea resultArea;
private double sum =0;
private double totalCredits=0;
private String code = "";
private String name = "";
private String credit = "";
private String grade = "";
private String heading = ("Code\tName\tCredit\tGrade" + "\n");
private ArrayList<Course> courseList;
private JButton AddCourse;
private JButton CalculateGPA;
private JButton ResetInput;
private JButton ResetOutput;
private static final int AREA_ROWS = 15;
private static final int AREA_COLUMNS = 35;
private final int FRAME_HEIGHT =400;
private final int FRAME_WIDTH = 500;
final int FIELD_WIDTH = 30;
public DegreeWorksFrame() {
resultArea = new JTextArea(AREA_ROWS, AREA_COLUMNS);
resultArea.setText(heading);
resultArea.setEditable(false);
createTextField1();
createTextField2();
createTextField3();
createTextField4();
createButtonAddCourse();
createButtonCalculateGPA();
createButtonResetInput();
createButtonResetOutput();
createPanel();
setSize(FRAME_WIDTH, FRAME_HEIGHT);
}
private void createTextField1() {
courseCodeLabel = new JLabel("Enter Course Code: ");
courseCodeField = new JTextField(FIELD_WIDTH);
courseCodeField.setText(code);
}
private void createTextField2() {
courseNameLabel = new JLabel("Enter Course Name: ");
courseNameField = new JTextField(FIELD_WIDTH);
courseNameField.setText(name);
}
private void createTextField3() {
courseCreditLabel = new JLabel("Enter Course Credit: ");
courseCreditField = new JTextField(FIELD_WIDTH);
courseCreditField.setText(credit);
}
private void createTextField4() {
courseGradeLabel = new JLabel("Enter Course Grade: ");
courseGradeField = new JTextField(FIELD_WIDTH);
courseGradeField.setText(grade);
}
private void createButtonAddCourse() {
AddCourse = new JButton ("Add Courses: ");
ActionListener listener = new addCourseListener();
AddCourse.addActionListener(listener);
}
class addCourseListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
courseList = new ArrayList();
String receiveList = userList.get
}
}
private void createButtonCalculateGPA() {
CalculateGPA = new JButton ("Calculate GPA");
ActionListener listener = new addCourseListener();
AddCourse.addActionListener(listener);
}
class calculateGPAListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
}
}
private void createButtonResetInput() {
ResetInput = new JButton ("Reset Input");
ActionListener listener = new addCourseListener();
AddCourse.addActionListener(listener);
}
class resetInputListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
}
}
private void createButtonResetOutput() {
ResetOutput = new JButton ("Reset Output");
ActionListener listener = new addCourseListener();
AddCourse.addActionListener(listener);
}
class resetOutputListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
}
}
private void createPanel() {
JPanel panel = new JPanel();
panel.add(courseCodeLabel);
panel.add(courseCodeField);
panel.add(courseNameLabel);
panel.add(courseNameField);
panel.add(courseCreditLabel);
panel.add(courseCreditField);
panel.add(courseGradeLabel);
panel.add(courseGradeField);
//buttons
panel.add(AddCourse);
panel.add(CalculateGPA);
panel.add(ResetInput);
panel.add(ResetOutput);
//Scroll bar
JScrollPane scrollPane = new JScrollPane(resultArea);
panel.add(scrollPane);
add(panel);
}
}
Side-note: Note you're adding multiple listeners to your AddCourse button which is not correct. You need to add the listeners to the proper buttons.
As stated in this answer a good approach to implement listeners is by using Anonymous Inner classes (see the linked answer for a better explanation about why).
For instance:
private void createButtonAddCourse() {
AddCourse = new JButton ("Add Courses: ");
AddCourse.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Create a new Course object and add it to the ArrayList here
}
});
}
...
private void createButtonCalculateGPA() {
CalculateGPA = new JButton ("Calculate GPA");
CalculateGPA.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// Iterate over the ArrayList and calculate the overall GPA for each course
}
});
}
Suggested readings
Anonymous Classes
Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods
in Java
Swing?
Using Layout
Managers

Categories