I'm writing this code for university, to read the user input and calculate the charges (its a hospital bill)
But when I press calculate the JTextArea displays 0 as value
I'm very much a newbie so any guidance would be appreciated
the code is:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class HospitalChargesCalculator extends JFrame implements ActionListener{
private JLabel hospitalStayLabel;
private JLabel medicationLabel;
private JLabel surgicalFeesLabel;
private JLabel labFeesLabel;
private JLabel rehabLabel;
private JLabel totalLabel;
private JTextField hospitalStayTF;
private JTextField medicationTF;
private JTextField surgicalFeesTF;
private JTextField labFeesTF;
private JTextField rehabTF;
private JTextArea totalChargesTA;
private JButton calculateB;
private JButton exitB;
public static final int WIDTH = 500;
public static final int HEIGHT = 350;
static int totalStayCharge;
static int totalMisc;
static int totalCharges;
static int totalDays;
static int totalMedication;
static int totalSurgical;
static int totalLab;
static int totalRehab;
public HospitalChargesCalculator() {
setTitle("Hospital Charges");
Container c = getContentPane();
setSize(WIDTH, HEIGHT);
c.setLayout(null);
hospitalStayLabel = new JLabel(" Number of days spent in hospital: ",
SwingConstants.LEFT);
medicationLabel = new JLabel(" Total Medication Charges: ",
SwingConstants.LEFT);
surgicalFeesLabel = new JLabel(" Total sugical charges : ",
SwingConstants.LEFT);
labFeesLabel = new JLabel(" Total lab fees: ",
SwingConstants.LEFT);
rehabLabel = new JLabel(" Total Rehab charges: ",
SwingConstants.LEFT);
totalLabel = new JLabel(" Total Charges: ",
SwingConstants.LEFT);
calculateB = new JButton("Calculate");
calculateB.addActionListener(this);
exitB = new JButton("Exit");
exitB.addActionListener(this);
hospitalStayTF = new JTextField();
medicationTF = new JTextField();
surgicalFeesTF = new JTextField();
labFeesTF = new JTextField();
rehabTF = new JTextField();
totalChargesTA = new JTextArea();
hospitalStayLabel.setSize(250, 30);
hospitalStayTF.setSize(200, 30);
medicationLabel.setSize(200, 30);
medicationTF.setSize(200, 30);
surgicalFeesLabel.setSize(200, 30);
surgicalFeesTF.setSize(200, 30);
labFeesLabel.setSize(200, 30);
labFeesTF.setSize(200, 30);
rehabLabel.setSize(200, 30);
rehabTF.setSize(200,30);
totalLabel.setSize(200, 30);
totalChargesTA.setSize(200,30);
calculateB.setSize(100, 30);
exitB.setSize(100, 30);
hospitalStayLabel.setLocation(30, 25);
hospitalStayTF.setLocation(250, 25);
medicationLabel.setLocation(30, 60);
medicationTF.setLocation(250, 60);
surgicalFeesLabel.setLocation(30, 95);
surgicalFeesTF.setLocation(250, 95);
labFeesLabel.setLocation(30, 130);
labFeesTF.setLocation(250, 130);
rehabLabel.setLocation(30, 165);
rehabTF.setLocation(250, 165);
totalLabel.setLocation(30, 250);
totalChargesTA.setLocation(250, 250);
calculateB.setLocation(70, 205);
exitB.setLocation(300, 205);
c.add(hospitalStayLabel);
c.add(hospitalStayTF);
c.add(medicationLabel);
c.add(medicationTF);
c.add(surgicalFeesLabel);
c.add(surgicalFeesTF);
c.add(labFeesLabel);
c.add(labFeesTF);
c.add(rehabLabel);
c.add(rehabTF);
c.add(totalLabel);
c.add(totalChargesTA);
c.add(calculateB);
c.add(exitB);
hospitalStayTF.addActionListener(this);
medicationTF.addActionListener(this);
surgicalFeesTF.addActionListener(this);
labFeesTF.addActionListener(this);
rehabTF.addActionListener(this);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformedGet(ActionEvent g)
{
totalDays = Integer.parseInt(hospitalStayTF.getText());
totalMedication = Integer.parseInt(medicationTF.getText());
totalSurgical = Integer.parseInt(surgicalFeesTF.getText());
totalLab = Integer.parseInt(labFeesTF.getText());
totalRehab = Integer.parseInt(rehabTF.getText());
}
public int CalcStayCharges()
{
int dailyCharge = 350;
totalStayCharge = totalDays * dailyCharge;
return totalStayCharge;
}
public int CalcMiscCharges()
{
totalMisc = (totalMedication + totalSurgical + totalLab + totalRehab);
return totalMisc;
}
public int CalcTotalCharges()
{
totalCharges = (totalStayCharge + totalMisc);
return totalCharges;
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("Calculate"))
{
totalChargesTA.setText(String.valueOf(totalCharges));
}
else if (e.getActionCommand().equals("Exit"))
System.exit(0);
}
public static void main(String[] args)
{
HospitalChargesCalculator hospCalc = new HospitalChargesCalculator();
}
}
if you press the button you simply execute actionPerformed(ActionEvent e), which only does totalChargesTA.setText(String.valueOf(totalCharges));. In order to get a value you should use any of your calculalationmethods before using the setText method.
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("Calculate"))
{
totalCharges = CalcTotalCharges();
totalChargesTA.setText(String.valueOf(totalCharges));
}
else if (e.getActionCommand().equals("Exit"))
System.exit(0);
}
it might be that you need to call some of the other methods aswell, if they are calculating the values that are used inside of CalcTotalCharges.
I cant comment yet, so here as an answer.
As said you dont actually call the function to calculate your total charges with totalChargesTA.setText(String.valueOf(totalCharges)); but instead try to directly access the variable totalCharges of your method CalcTotalCharges() (the method you should be calling here), this is only possible because you declared all your variables as static int so you can access them even in parts of your code where you dont actually want to access them.
Dont declare all your variables static, and you would have seen the error of not calling the methods. Think about which variables need to be static and reduce it to those.
Also dont declare all your variables you are going to use in just that one function in your class, inistead declare them in that function, so that you avoid the same error as with your static declarations.
-- Also, additionaly the answer provided by Subin Thomas that shows the principal error in your code, his solution wont work because he mixed up some of the functions and you also have to fix the function:
public int CalcTotalCharges()
{
totalCharges = (totalStayCharge + totalMisc);
return totalCharges;
}
Where you have the same kind of error to:
public int CalcTotalCharges()
{
totalCharges = (CalcStayCharges() + CalcMiscCharges());
return totalCharges;
}
EDIT: Actually you also have another error in the way you retrieve the values from you input textfields. Why did you use the method public void actionPerformedGet(ActionEvent g) ?
This wont work with your ActionListener. Instead copy the code in this function to your actionPerformed Method. Then it will actually work. For completeness here the working code:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class HospitalChargesCalculator extends JFrame implements ActionListener{
private JLabel hospitalStayLabel;
private JLabel medicationLabel;
private JLabel surgicalFeesLabel;
private JLabel labFeesLabel;
private JLabel rehabLabel;
private JLabel totalLabel;
private JTextField hospitalStayTF;
private JTextField medicationTF;
private JTextField surgicalFeesTF;
private JTextField labFeesTF;
private JTextField rehabTF;
private JTextArea totalChargesTA;
private JButton calculateB;
private JButton exitB;
public static final int WIDTH = 500;
public static final int HEIGHT = 350;
int totalDays;
int totalMedication;
int totalSurgical;
int totalLab;
int totalRehab;
public HospitalChargesCalculator() {
setTitle("Hospital Charges");
Container c = getContentPane();
setSize(WIDTH, HEIGHT);
c.setLayout(null);
hospitalStayLabel = new JLabel(" Number of days spent in hospital: ",
SwingConstants.LEFT);
medicationLabel = new JLabel(" Total Medication Charges: ",
SwingConstants.LEFT);
surgicalFeesLabel = new JLabel(" Total sugical charges : ",
SwingConstants.LEFT);
labFeesLabel = new JLabel(" Total lab fees: ",
SwingConstants.LEFT);
rehabLabel = new JLabel(" Total Rehab charges: ",
SwingConstants.LEFT);
totalLabel = new JLabel(" Total Charges: ",
SwingConstants.LEFT);
calculateB = new JButton("Calculate");
calculateB.addActionListener(this);
exitB = new JButton("Exit");
exitB.addActionListener(this);
hospitalStayTF = new JTextField();
medicationTF = new JTextField();
surgicalFeesTF = new JTextField();
labFeesTF = new JTextField();
rehabTF = new JTextField();
totalChargesTA = new JTextArea();
hospitalStayLabel.setSize(250, 30);
hospitalStayTF.setSize(200, 30);
medicationLabel.setSize(200, 30);
medicationTF.setSize(200, 30);
surgicalFeesLabel.setSize(200, 30);
surgicalFeesTF.setSize(200, 30);
labFeesLabel.setSize(200, 30);
labFeesTF.setSize(200, 30);
rehabLabel.setSize(200, 30);
rehabTF.setSize(200,30);
totalLabel.setSize(200, 30);
totalChargesTA.setSize(200,30);
calculateB.setSize(100, 30);
exitB.setSize(100, 30);
hospitalStayLabel.setLocation(30, 25);
hospitalStayTF.setLocation(250, 25);
medicationLabel.setLocation(30, 60);
medicationTF.setLocation(250, 60);
surgicalFeesLabel.setLocation(30, 95);
surgicalFeesTF.setLocation(250, 95);
labFeesLabel.setLocation(30, 130);
labFeesTF.setLocation(250, 130);
rehabLabel.setLocation(30, 165);
rehabTF.setLocation(250, 165);
totalLabel.setLocation(30, 250);
totalChargesTA.setLocation(250, 250);
calculateB.setLocation(70, 205);
exitB.setLocation(300, 205);
c.add(hospitalStayLabel);
c.add(hospitalStayTF);
c.add(medicationLabel);
c.add(medicationTF);
c.add(surgicalFeesLabel);
c.add(surgicalFeesTF);
c.add(labFeesLabel);
c.add(labFeesTF);
c.add(rehabLabel);
c.add(rehabTF);
c.add(totalLabel);
c.add(totalChargesTA);
c.add(calculateB);
c.add(exitB);
hospitalStayTF.addActionListener(this);
medicationTF.addActionListener(this);
surgicalFeesTF.addActionListener(this);
labFeesTF.addActionListener(this);
rehabTF.addActionListener(this);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}
public int CalcStayCharges()
{
int dailyCharge = 350;
int totalStayCharge = totalDays * dailyCharge;
return totalStayCharge;
}
public int CalcMiscCharges()
{
int totalMisc = (totalMedication + totalSurgical + totalLab + totalRehab);
return totalMisc;
}
public int CalcTotalCharges()
{
int totalCharges = (CalcStayCharges() + CalcMiscCharges());
return totalCharges;
}
public void actionPerformed(ActionEvent e)
{
totalDays = Integer.parseInt(hospitalStayTF.getText());
totalMedication = Integer.parseInt(medicationTF.getText());
totalSurgical = Integer.parseInt(surgicalFeesTF.getText());
totalLab = Integer.parseInt(labFeesTF.getText());
totalRehab = Integer.parseInt(rehabTF.getText());
if (e.getActionCommand().equals("Calculate"))
{
totalChargesTA.setText(CalcTotalCharges()+"");
}
else if (e.getActionCommand().equals("Exit"))
System.exit(0);
}
public static void main(String[] args)
{
HospitalChargesCalculator hospCalc = new HospitalChargesCalculator();
}
}
Related
I have a JFrame with two JPanel. Two buttons. The app starts with no panels, just buttons. Upon pressing a button I want I display one panel, and then upon pressing another button I substitute one panel with another one and vice versa. I have this code, but it doesn't really work. The panels (when one button is clicked and then another) appear on top of each other. Any help would be appreciated!
Thank you in advance!
Main.java
import javax.swing.*;
import javax.swing.text.View;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Main {
static JButton enterDataButton = new JButton("Enter Data");
static JButton viewDataButton = new JButton("View Data");
static int yPosition = 10;
static int xLabelPosition = 20;
static int xFieldPosition = 20;
static int labelWidth = 200;
static int fieldWidth = 200;
public static void main (String[] args) {
final JFrame frame = new JFrame("SimpleTrans Main Window");
JFrame.setDefaultLookAndFeelDecorated(true);
frame.setBounds(100, 100, 1200, 800);
frame.getContentPane().setLayout(null);
JPanel mainPanel = new JPanel();
enterDataButton.setBounds(xFieldPosition, yPosition, fieldWidth, 30);
enterDataButton.setForeground(Color.DARK_GRAY);
final InputDataArea inputDataArea = new InputDataArea();
final ViewDataArea viewDataArea = new ViewDataArea();
enterDataButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("enterData Button Pressed!");
frame.remove(viewDataArea);
inputDataArea.InputDataArea(frame.getContentPane());
frame.add(inputDataArea);
frame.getContentPane().invalidate();
frame.getContentPane().validate();
frame.getContentPane().repaint();
}
});
viewDataButton.setBounds(xFieldPosition + fieldWidth, yPosition, fieldWidth, 30);
viewDataButton.setForeground(Color.DARK_GRAY);
viewDataButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("viewData Button Pressed!");
frame.remove(inputDataArea);
viewDataArea.ViewDataArea(frame.getContentPane());
frame.add(viewDataArea);
frame.getContentPane().revalidate();
frame.getContentPane().validate();
frame.getContentPane().repaint();
}
});
frame.getContentPane().add(enterDataButton);
frame.getContentPane().add(viewDataButton);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
InputDataArea.java
import javax.swing.*;
import java.awt.*;
public class InputDataArea extends JPanel {
private DataTextField textFieldTripNumber = new DataTextField();
private DataTextField textFieldExportCountry = new DataTextField();
private DataTextField textFieldDestinationCountry = new DataTextField();
private DataTextField textFieldPriceFixed = new DataTextField();
JLabel textFieldLabelTripNumber = new JLabel("Trip Number:");
JLabel textFieldLabelExportCountry = new JLabel("Export Country:");
JLabel textFieldLabelDestinationCountry = new JLabel("Destination Country:");
JLabel textFieldLabelPriceFixed = new JLabel("Price Fixed:");
JButton saveButton = new JButton("Save");
JButton emptyButton = new JButton("Empty");
int yPosition = 60;
int xLabelPosition = 20;
int xFieldPosition = 220;
int labelWidth = 200;
int fieldWidth = 200;
public void InputDataArea(Container pane) {
textFieldLabelTripNumber.setBounds(xLabelPosition, yPosition, labelWidth, 20);
pane.add(textFieldLabelTripNumber);
textFieldTripNumber.setColumns(20);
textFieldTripNumber.setBounds(xFieldPosition, yPosition, fieldWidth, 20);
pane.add(textFieldTripNumber);
textFieldLabelExportCountry.setBounds(xLabelPosition, yPosition + 30, labelWidth, 20);
pane.add(textFieldLabelExportCountry);
textFieldExportCountry.setColumns(20);
textFieldExportCountry.setBounds(xFieldPosition, yPosition + 30, fieldWidth, 20);
pane.add(textFieldExportCountry);
textFieldLabelDestinationCountry.setBounds(xLabelPosition, yPosition + 60, labelWidth, 20);
pane.add(textFieldLabelDestinationCountry);
textFieldDestinationCountry.setColumns(20);
textFieldDestinationCountry.setBounds(xFieldPosition, yPosition + 60, fieldWidth, 20);
pane.add(textFieldDestinationCountry);
textFieldLabelPriceFixed.setBounds(xLabelPosition, yPosition + 90, labelWidth, 20);
pane.add(textFieldLabelPriceFixed);
textFieldPriceFixed.setColumns(20);
textFieldPriceFixed.setBounds(xFieldPosition, yPosition + 90, fieldWidth, 20);
pane.add(textFieldPriceFixed);
saveButton.setBounds(xFieldPosition, yPosition + 130, fieldWidth, 50);
saveButton.setForeground(Color.GREEN);
pane.add(saveButton);
emptyButton.setBounds(xFieldPosition + fieldWidth, yPosition + 130, fieldWidth, 50);
emptyButton.setForeground(Color.RED);
pane.add(emptyButton);
}
}
ViewDataArea.java
import javax.swing.*;
import java.awt.*;
public class ViewDataArea extends JPanel {
private DataTextField textFieldTripNumber = new DataTextField();
private DataTextField textFieldExportCountry = new DataTextField();
private DataTextField textFieldDestinationCountry = new DataTextField();
private DataTextField textFieldPriceFixed = new DataTextField();
JLabel textFieldLabelViewData = new JLabel("ViewData");
JButton saveButton = new JButton("Save");
JButton emptyButton = new JButton("Empty");
int yPosition = 60;
int xLabelPosition = 20;
int xFieldPosition = 220;
int labelWidth = 200;
int fieldWidth = 200;
public void ViewDataArea(Container pane) {
textFieldLabelViewData.setBounds(xLabelPosition, yPosition, labelWidth, 20);
pane.add(textFieldLabelViewData);
}
}
DataTextField.java
import javax.swing.*;
import java.util.ArrayList;
import java.util.List;
public class DataTextField extends JTextField {
private List<JTextField> textFields = new ArrayList<JTextField>();
public void addTextField(JTextField textField) {
textFields.add(textField);
}
}
YOu should be using a Card Layout. A Card Layout is specifically designed to display multiple components in the same place. The Card Layout will reserve space for the largest component and then you just swap components as required.
Read the section from the Swing tutorial on How to Use Card Layout for more information at a working example.
So I am working on a project for a class because I am trying to learn this lovely thing called Java. Well anyway I am trying to get some methods to print out in the TextArea in my JPanel.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class GUI_Amortization_Calculator extends JFrame {
private JPanel contentPane;
private JTextField textLoanAmount;
private JTextField textYears;
private JTextField textInterestRate;
TextArea calculation;
/**
* #wbp.nonvisual location=71,9
*/
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI_Amortization_Calculator frame = new GUI_Amortization_Calculator();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public GUI_Amortization_Calculator() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 650, 600);
getContentPane().setLayout(null);
JPanel panel_2 = new JPanel();
panel_2.setBounds(10, 11, 614, 34);
getContentPane().add(panel_2);
JLabel IntroLabel = new JLabel("Introduction to Java Class GUI Amortization Mortgage Calculator by Beth Pizana");
IntroLabel.setForeground(Color.MAGENTA);
IntroLabel.setFont(new Font("Arial Black", Font.BOLD, 12));
panel_2.add(IntroLabel);
JPanel panel = new JPanel();
panel.setBounds(10, 56, 198, 495);
getContentPane().add(panel);
JLabel loanAmountLabel = new JLabel("Enter your loan amount:");
loanAmountLabel.setFont(new Font("Arial", Font.PLAIN, 12));
panel.add(loanAmountLabel);
textLoanAmount = new JTextField();
textLoanAmount.setFont(new Font("Arial", Font.PLAIN, 12));
panel.add(textLoanAmount);
textLoanAmount.setColumns(15);
String txtLoanAmount = textLoanAmount.getText();
JLabel yearsLabel = new JLabel("Enter the years of your loan:");
yearsLabel.setFont(new Font("Arial", Font.PLAIN, 12));
panel.add(yearsLabel);
textYears = new JTextField();
textYears.setFont(new Font("Arial", Font.PLAIN, 12));
panel.add(textYears);
textYears.setColumns(15);
String txtYears = textYears.getText();
JLabel interestRateLavel = new JLabel("Enter the interest rate of your loan:");
interestRateLavel.setFont(new Font("Arial", Font.PLAIN, 12));
panel.add(interestRateLavel);
textInterestRate = new JTextField();
textInterestRate.setFont(new Font("Arial", Font.PLAIN, 12));
panel.add(textInterestRate);
textInterestRate.setColumns(15);
String txtInterestRate = textInterestRate.getText();
JButton calculate = new JButton("Calculate");
calculate.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
Double loanAmount = Double.parseDouble(txtLoanAmount);
int years = Integer.parseInt(txtYears);
Double interestRate = Double.parseDouble(txtInterestRate);
String calc = calculation.getText(calcAmortization(loanAmount, years, interestRate));
textarea.append(calc);
}
});
calculate.setFont(new Font("Arial", Font.PLAIN, 12));
panel.add(calculate);
JButton reset = new JButton("Reset");
reset.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
textLoanAmount.setText("");
textYears.setText("");
textInterestRate.setText("");
}
});
reset.setFont(new Font("Arial", Font.PLAIN, 12));
panel.add(reset);
TextArea calculation = new TextArea();
calculation.setColumns(6);
calculation.setBounds(228, 51, 380, 500);
getContentPane().add(calculation);
JScrollBar scrollBar = new JScrollBar();
scrollBar.setBounds(591, 56, 17, 477);
getContentPane().add(scrollBar);
JScrollBar scrollBar_1 = new JScrollBar();
scrollBar_1.setOrientation(JScrollBar.HORIZONTAL);
scrollBar_1.setBounds(231, 534, 363, 17);
getContentPane().add(scrollBar_1);
}
public static void calcAmortization(double loanAmount, int numYears, double interestRate){
double newBalance;
//Calculate the monthly interest rate
double monthlyInterestRate = (interestRate / 12)/100;
//Calculate the number of months
int totalMonths = numYears * 12;
double monthlyPayment, interestPayment, principalPayment;
int count;
//Calculate the monthly payment
monthlyPayment = loanAmount * monthlyInterestRate * Math.pow(1 + monthlyInterestRate, (double)totalMonths)/(Math.pow(1 + monthlyInterestRate, (double)totalMonths)-1);
printTableHeader();
for (count = 1; count < totalMonths; count++){
interestPayment = loanAmount * monthlyInterestRate;
principalPayment = monthlyPayment - interestPayment;
newBalance = loanAmount - principalPayment;
printSchedule(count, loanAmount, monthlyPayment, interestPayment, principalPayment, newBalance);
loanAmount = newBalance;
}
}
public static void printSchedule(int count, double loanAmount, double monthlyPayment, double interestPayment, double principalPayment, double newBalance){
System.out.format("%-8d$%,-12.2f$%,-10.2f$%,-10.2f$%,-10.2f$%,-12.2f\n",count,loanAmount,monthlyPayment,interestPayment,principalPayment,newBalance);
}
public static void printTableHeader(){
int count;
System.out.println("\nAmortization Schedule for Borrower");
for(count=0;count<62;count++) System.out.print("-");
System.out.format("\n%-10s%-11s%-12s%-11s%-11s%-12s"," ","Old","Monthly","Interest","Principal","New","Balance");
System.out.format("\n%-10s%-11s%-12s%-11s%-11s%-12s\n\n","Month","Balance","Payment","Paid","Paid","Balance");
}
}
I have already figured out that the lines below are the problem and I have tried a number of different ways to make it work. I am sort of at my wits end. I have read a number things about sending to the textArea but having difficulty finding ones with methods. Please help or at least send me in the right direction. Thanks very much. Here is the problem area:
String calc = calculation.getText(calcAmortization(loanAmount, years, interestRate));
textarea.append(calc);
Update
I got it working by expanding on the ideas you guys gave me and I also added a Scroll Pane. The scroll bar is not showing up so if anyone can give me some advice as to why the scroll pane is not working properly.
New working code except the scroll pane:
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
#SuppressWarnings("serial")
public class GUI_Amortization_Calculator extends JFrame {
private JPanel contentPane;
private JTextField textLoanAmount;
private JTextField textYears;
private JTextField textInterestRate;
//private JTextArea calculation;
private PrintStream standardOut;
/**
* #wbp.nonvisual location=71,9
*/
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI_Amortization_Calculator frame = new GUI_Amortization_Calculator();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public GUI_Amortization_Calculator() {
class SpecialOutput extends OutputStream {
private JTextArea calculation;
public SpecialOutput(JTextArea calculation) {
this.calculation = calculation;
}
#Override
public void write(int b) throws IOException {
// redirects data to the text area
calculation.append(String.valueOf((char)b));
// scrolls the text area to the end of data
calculation.setCaretPosition(calculation.getDocument().getLength());
};
}
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 950, 650);
getContentPane().setLayout(null);
JPanel panel_2 = new JPanel();
panel_2.setBounds(10, 11, 614, 34);
getContentPane().add(panel_2);
JLabel IntroLabel = new JLabel("Introduction to Java Class GUI Amortization Mortgage Calculator by Beth Pizana");
IntroLabel.setForeground(Color.MAGENTA);
IntroLabel.setFont(new Font("Arial Black", Font.BOLD, 12));
panel_2.add(IntroLabel);
JPanel panel = new JPanel();
panel.setBounds(10, 56, 198, 545);
getContentPane().add(panel);
JLabel loanAmountLabel = new JLabel("Enter your loan amount:");
loanAmountLabel.setFont(new Font("Arial", Font.PLAIN, 12));
panel.add(loanAmountLabel);
JTextField textLoanAmount = new JTextField();
textLoanAmount.setFont(new Font("Arial", Font.PLAIN, 12));
panel.add(textLoanAmount);
textLoanAmount.setColumns(15);
//String txtLoanAmount = textLoanAmount.getText();
JLabel yearsLabel = new JLabel("Enter the years of your loan:");
yearsLabel.setFont(new Font("Arial", Font.PLAIN, 12));
panel.add(yearsLabel);
JTextField textYears = new JTextField();
textYears.setFont(new Font("Arial", Font.PLAIN, 12));
panel.add(textYears);
textYears.setColumns(15);
//String txtYears = textYears.getText();
JLabel interestRateLavel = new JLabel("Enter the interest rate of your loan:");
interestRateLavel.setFont(new Font("Arial", Font.PLAIN, 12));
panel.add(interestRateLavel);
JTextField textInterestRate = new JTextField();
textInterestRate.setFont(new Font("Arial", Font.PLAIN, 12));
panel.add(textInterestRate);
textInterestRate.setColumns(15);
//String txtInterestRate = textInterestRate.getText();
JButton calculate = new JButton("Calculate");
calculate.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
double loanAmount = Double.parseDouble(textLoanAmount.getText());
int years = Integer.parseInt(textYears.getText());
double interestRate = Double.parseDouble(textInterestRate.getText());
calcAmortization(loanAmount, years, interestRate);
//String calc = calculation.getText();
//calculation.append(calc);
}
});
calculate.setFont(new Font("Arial", Font.PLAIN, 12));
panel.add(calculate);
JButton reset = new JButton("Reset");
reset.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
textLoanAmount.setText(null);
textYears.setText(null);
textInterestRate.setText(null);
}
});
reset.setFont(new Font("Arial", Font.PLAIN, 12));
panel.add(reset);
JTextArea calculation = new JTextArea();
calculation.setBounds(228, 51, 680, 550);
PrintStream printStream = new PrintStream(new SpecialOutput(calculation));
getContentPane().add(calculation);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setBounds(228, 51, 680, 550);
getContentPane().add(scrollPane);
standardOut = System.out;
System.setOut(printStream);
System.setErr(printStream);
}
public static void calcAmortization(double loanAmount, int numYears, double interestRate){
double newBalance;
//Calculate the monthly interest rate
double monthlyInterestRate = (interestRate / 12)/100;
//Calculate the number of months
int totalMonths = numYears * 12;
double monthlyPayment, interestPayment, principalPayment;
int count;
//Calculate the monthly payment
monthlyPayment = loanAmount * monthlyInterestRate * Math.pow(1 + monthlyInterestRate, (double)totalMonths)/(Math.pow(1 + monthlyInterestRate, (double)totalMonths)-1);
printTableHeader();
for (count = 1; count < totalMonths; count++){
interestPayment = loanAmount * monthlyInterestRate;
principalPayment = monthlyPayment - interestPayment;
newBalance = loanAmount - principalPayment;
printSchedule(count, loanAmount, monthlyPayment, interestPayment, principalPayment, newBalance);
loanAmount = newBalance;
}
}
public static void printSchedule(int count, double loanAmount, double monthlyPayment, double interestPayment, double principalPayment, double newBalance){
System.out.format("%-8d$%,-12.2f$%,-10.2f$%,-10.2f$%,-10.2f$%,-12.2f\n",count,loanAmount,monthlyPayment,interestPayment,principalPayment,newBalance);
}
public static void printTableHeader(){
int count;
System.out.println("\nAmortization Schedule for Borrower");
for(count=0;count<62;count++) System.out.print("-");
System.out.format("\n%-10s%-11s%-12s%-11s%-11s%-12s"," ","Old","Monthly","Interest","Principal","New","Balance");
System.out.format("\n%-10s%-11s%-12s%-11s%-11s%-12s\n\n","Month","Balance","Payment","Paid","Paid","Balance");
}
}
A few things were wrong in your code:
Use JTextArea instead of TextArea (so everything is Swing)
The field calculation was not used, because you created a new local variable in your code TextArea calculation = new TextArea();
The local variables such as String txtLoanAmount = textLoanAmount.getText(); are useless! txtLoanAmount is not a permanent reference to the content of textLoanAmount. It is just a snapshot of the content of the text field at this instant (which is: "", because you just created the text field).
Your calcAmortization() method is correct, but it prints to standard output, not to the calculation text area, nor to a string that you could append to the text area. So I just redirected the standard output to your text area, to rewrite as little code as possible.
Instead of using a null layout and setBound() on each component, you should probably use a real layout, such as GridBagLayout (that, I did not fix).
.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class GUI_Amortization_Calculator extends JFrame {
private JPanel contentPane;
private JTextField textLoanAmount;
private JTextField textYears;
private JTextField textInterestRate;
private JTextArea calculation;
/**
* #wbp.nonvisual location=71,9
*/
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GUI_Amortization_Calculator frame = new GUI_Amortization_Calculator();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public GUI_Amortization_Calculator() {
System.setOut(new PrintStream(new OutputStream(){
#Override
public void write(int b) throws IOException {
// redirects data to the text area
calculation.append(String.valueOf((char)b));
// scrolls the text area to the end of data
calculation.setCaretPosition(calculation.getDocument().getLength());
}
}));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 650, 600);
getContentPane().setLayout(null);
JPanel panel_2 = new JPanel();
panel_2.setBounds(10, 11, 614, 34);
getContentPane().add(panel_2);
JLabel IntroLabel = new JLabel("Introduction to Java Class GUI Amortization Mortgage Calculator by Beth Pizana");
IntroLabel.setForeground(Color.MAGENTA);
IntroLabel.setFont(new Font("Arial Black", Font.BOLD, 12));
panel_2.add(IntroLabel);
JPanel panel = new JPanel();
panel.setBounds(10, 56, 198, 495);
getContentPane().add(panel);
JLabel loanAmountLabel = new JLabel("Enter your loan amount:");
loanAmountLabel.setFont(new Font("Arial", Font.PLAIN, 12));
panel.add(loanAmountLabel);
textLoanAmount = new JTextField();
textLoanAmount.setFont(new Font("Arial", Font.PLAIN, 12));
panel.add(textLoanAmount);
textLoanAmount.setColumns(15);
//String txtLoanAmount = textLoanAmount.getText();
JLabel yearsLabel = new JLabel("Enter the years of your loan:");
yearsLabel.setFont(new Font("Arial", Font.PLAIN, 12));
panel.add(yearsLabel);
textYears = new JTextField();
textYears.setFont(new Font("Arial", Font.PLAIN, 12));
panel.add(textYears);
textYears.setColumns(15);
//String txtYears = textYears.getText();
JLabel interestRateLavel = new JLabel("Enter the interest rate of your loan:");
interestRateLavel.setFont(new Font("Arial", Font.PLAIN, 12));
panel.add(interestRateLavel);
textInterestRate = new JTextField();
textInterestRate.setFont(new Font("Arial", Font.PLAIN, 12));
panel.add(textInterestRate);
textInterestRate.setColumns(15);
//String txtInterestRate = textInterestRate.getText();
JButton calculate = new JButton("Calculate");
calculate.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
Double loanAmount = Double.parseDouble(textLoanAmount.getText());
int years = Integer.parseInt(textYears.getText());
Double interestRate = Double.parseDouble(textInterestRate.getText());
//String calc = calculation.getText();
calcAmortization(loanAmount, years, interestRate);
//textarea.append(calc);
}
});
calculate.setFont(new Font("Arial", Font.PLAIN, 12));
panel.add(calculate);
JButton reset = new JButton("Reset");
reset.addMouseListener(new MouseAdapter() {
#Override
public void mousePressed(MouseEvent e) {
textLoanAmount.setText("");
textYears.setText("");
textInterestRate.setText("");
}
});
reset.setFont(new Font("Arial", Font.PLAIN, 12));
panel.add(reset);
calculation = new JTextArea();
calculation.setColumns(6);
JScrollPane p = new JScrollPane(calculation);
p.setBounds(228, 51, 380, 500);
getContentPane().add(p);
}
public static void calcAmortization(double loanAmount, int numYears, double interestRate){
double newBalance;
//Calculate the monthly interest rate
double monthlyInterestRate = (interestRate / 12)/100;
//Calculate the number of months
int totalMonths = numYears * 12;
double monthlyPayment, interestPayment, principalPayment;
int count;
//Calculate the monthly payment
monthlyPayment = loanAmount * monthlyInterestRate * Math.pow(1 + monthlyInterestRate, (double)totalMonths)/(Math.pow(1 + monthlyInterestRate, (double)totalMonths)-1);
printTableHeader();
for (count = 1; count < totalMonths; count++){
interestPayment = loanAmount * monthlyInterestRate;
principalPayment = monthlyPayment - interestPayment;
newBalance = loanAmount - principalPayment;
printSchedule(count, loanAmount, monthlyPayment, interestPayment, principalPayment, newBalance);
loanAmount = newBalance;
}
}
public static void printSchedule(int count, double loanAmount, double monthlyPayment, double interestPayment, double principalPayment, double newBalance){
System.out.format("%-8d$%,-12.2f$%,-10.2f$%,-10.2f$%,-10.2f$%,-12.2f\n",count,loanAmount,monthlyPayment,interestPayment,principalPayment,newBalance);
}
public static void printTableHeader(){
int count;
System.out.println("\nAmortization Schedule for Borrower");
for(count=0;count<62;count++) System.out.print("-");
System.out.format("\n%-10s%-11s%-12s%-11s%-11s%-12s"," ","Old","Monthly","Interest","Principal","New","Balance");
System.out.format("\n%-10s%-11s%-12s%-11s%-11s%-12s\n\n","Month","Balance","Payment","Paid","Paid","Balance");
}
}
Notice this bit, which redirects everything your print with System.out.print():
System.setOut(new PrintStream(new OutputStream(){
#Override
public void write(int b) throws IOException {
// redirects data to the text area
calculation.append(String.valueOf((char)b));
// scrolls the text area to the end of data
calculation.setCaretPosition(calculation.getDocument().getLength());
}
}));
Here variables txtLoanAmount, txtYears, txtInterestRate etc you have declared in the constructor. So they exists only in the scope of the function where they are declared. But u are using those variable inside another class, which does not make sense,
calculate.addMouseListener(new MouseAdapter() { // anonymous class
#Override
public void mousePressed(MouseEvent e) {
}
});
This is anonymous class. Because it has no name.
So you should do the following,
declare those variables final. or
make them instance variables by declaring them outside of the constructor.
I am looking for help to debug this program that I have written there are, no errors but the goal is to create a frame with three panels inside of it each of which has a titled border. I am having difficulty because my prompt requires of me to make 2 constructors and 2 classes so when I call the DailySales class in main I feel it doesn't include the other class.
So basically how can I make the panels show up while still keeping two classes and two constructors and how would I add titled borders to each of the JPanels, sorry but I'm having difficulty with the Oracle tutorial.
import java.awt.*;
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.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class DailySales extends JPanel {
final int lPizzaPrice = 12;
final int mPizzaPrice = 9;
final int sPizzaPrice = 6;
final int bSticksPrice = 3;
final double tax = .06;
final int dailyOper = 1000;
String lPizza;
String mPizza;
String sPizza;
String bSticks;
int largePizza;
int mediumPizza;
int smallPizza;
int breadSticks;
int totalLargePizza;
int totalMediumPizza;
int totalSmallPizza;
int totalBreadSticks;
int totalSales;
double totalTax;
double netSales;
int operCost;
double profit;
private FlowLayout dailyFlow;
private Container container;
JLabel lPizzaLabel = new JLabel("Large Pizza");//creating labels
JLabel mPizzaLabel = new JLabel("Medium Pizza");
JLabel sPizzaLabel = new JLabel("Small Pizza");
JLabel bSticksLabel = new JLabel("Bread Sticks");
JLabel totalSalesLabel = new JLabel("Total Sales");
JLabel totalTaxLabel = new JLabel("Total Tax");
JLabel netSalesLabel = new JLabel("Net Sales");
JLabel dailyCostLabel = new JLabel("Daily Oper Cost");
JLabel profitLabel = new JLabel("Profit or Loss");
JTextField largeField = new JTextField(10);
JTextField mediumField = new JTextField(10);
JTextField smallField = new JTextField(10);
JTextField breadField = new JTextField(10);
JTextField totalLargeField = new JTextField(10);
JTextField totalMediumField = new JTextField(10);
JTextField totalSmallField = new JTextField(10);
JTextField totalBreadField = new JTextField(10);
JTextField totalSalesField = new JTextField(10);
JTextField totalTaxField = new JTextField(10);
JTextField netSalesField = new JTextField(10);
JTextField dailyCostField = new JTextField(10);
JTextField profitField = new JTextField(10);
JButton clearButton = new JButton("Clear Fields");//Creating buttons
JButton calculateButton = new JButton("Calculate");
JButton exitButton = new JButton("Exit");
JPanel subPanel1 = new JPanel();
JPanel subPanel2 = new JPanel();
JPanel subPanel3 = new JPanel();
JPanel top = new JPanel();
public class GUI extends JPanel {
public GUI() {
subPanel1.setLayout(dailyFlow);
subPanel1.add(lPizzaLabel, largeField);
subPanel1.add(mPizzaLabel, mediumField);
subPanel1.add(sPizzaLabel, smallField);
subPanel1.add(bSticksLabel, breadField);
subPanel1.setSize(100, 100);
subPanel2.setLayout(dailyFlow);
subPanel2.add(totalLargeField);
subPanel2.add(totalMediumField);
subPanel2.add(totalSmallField);
subPanel2.add(totalBreadField);
subPanel3.setLayout(dailyFlow);
subPanel3.add(totalSalesLabel, totalSalesField);
subPanel3.add(totalTaxLabel, totalTaxField);
subPanel3.add(netSalesLabel, netSalesField);
subPanel3.add(dailyCostLabel, dailyCostField);
subPanel3.add(profitLabel, profitField);
top.setBackground(Color.red);
JLabel title = new JLabel("Eve's Pizza Daily Sales");
title.setFont(new Font("Helvetica", 1, 14));
top.add(title);
totalSalesField.setEditable(false);//making total field uneditable
totalTaxField.setEditable(false);
netSalesField.setEditable(false);
dailyCostField.setEditable(false);
profitField.setEditable(false);
}
}
public DailySales() //creating a constructor
{
/**
* The constructor with all the layout informations and operators
*
*
* Also adding all labels, textfields, and buttons to frame. making the
* total field uneditable
*/
JFrame frame = new JFrame();
frame.add(subPanel1);
frame.add(subPanel2);
frame.add(subPanel3);
frame.add(top);
frame.setSize(600, 450);
frame.setVisible(true);
clearButton.addActionListener(new ActionListener() {//initial button removes all entered text
public void actionPerformed(ActionEvent e) {
largeField.setText("");
mediumField.setText("");
smallField.setText("");
breadField.setText("");
totalLargeField.setText("");
totalMediumField.setText("");
totalSmallField.setText("");
totalBreadField.setText("");
totalSalesField.setText("");
totalTaxField.setText("");
netSalesField.setText("");
dailyCostField.setText("");
profitField.setText("");
}
});
calculateButton.addActionListener(new ActionListener() {//update button calculates all the inputs and displays everything
public void actionPerformed(ActionEvent e) {
lPizza = largeField.getText();
mPizza = mediumField.getText();
sPizza = smallField.getText();
bSticks = breadField.getText();
largePizza = Integer.parseInt(lPizza);
mediumPizza = Integer.parseInt(mPizza);
smallPizza = Integer.parseInt(sPizza);
breadSticks = Integer.parseInt(bSticks);
totalLargePizza = (lPizzaPrice * largePizza);
totalMediumPizza = (mPizzaPrice * mediumPizza);
totalSmallPizza = (sPizzaPrice * smallPizza);
totalBreadSticks = (bSticksPrice * breadSticks);
totalLargeField.setText("" + totalLargePizza);
totalMediumField.setText("" + totalMediumPizza);
totalSmallField.setText("" + totalSmallPizza);
totalBreadField.setText("" + totalBreadSticks);
totalSales = (totalLargePizza + totalMediumPizza + totalSmallPizza + totalBreadSticks);
totalTax = (totalSales * tax);
netSales = (totalSales - totalTax);
profit = (netSales - dailyOper);
/**
* calculates total by adding all entered values if else
* statements for different situations that calculate the
* different between total and diet
*/
if (profit > 0) {
profitLabel.setText("Profit of ");
} else if (profit < 0) {
profitLabel.setText("Loss of ");
} else if (profit == 0) {
profitLabel.setText("No profit or loss ");
}
if (largePizza < 0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (mediumPizza < 0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (smallPizza < 0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (breadSticks < 0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
}
}
});
exitButton.addActionListener(new ActionListener() {//close button closes the program when clicked on
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
new DailySales();
}
}
There's still a lot you can do to make this better, but this works.
public class DailySales extends JPanel {
final int lPizzaPrice = 12, mPizzaPrice = 9, sPizzaPrice = 6, bSticksPrice = 3;
final double tax = .06;
final int dailyOper = 1000;
String lPizza, mPizza, sPizza, bSticks;
int largePizza, mediumPizza, smallPizza, breadSticks, totalLargePizza,
totalMediumPizza, totalSmallPizza, totalBreadSticks;
int totalSales;
double totalTax;
double netSales;
int operCost;
double profit;
JLabel lPizzaLabel = new JLabel("Large Pizza");
JLabel mPizzaLabel = new JLabel("Medium Pizza");
JLabel sPizzaLabel = new JLabel("Small Pizza");
JLabel bSticksLabel = new JLabel("Bread Sticks");
JLabel totalSalesLabel = new JLabel("Total Sales");
JLabel totalTaxLabel = new JLabel("Total Tax");
JLabel netSalesLabel = new JLabel("Net Sales");
JLabel dailyCostLabel = new JLabel("Daily Oper Cost");
JLabel profitLabel = new JLabel("Profit or Loss");
JTextField largeField = new JTextField(10);
JTextField mediumField = new JTextField(10);
JTextField smallField = new JTextField(10);
JTextField breadField = new JTextField(10);
JTextField totalLargeField = new JTextField(10);
JTextField totalMediumField = new JTextField(10);
JTextField totalSmallField = new JTextField(10);
JTextField totalBreadField = new JTextField(10);
JTextField totalSalesField = new JTextField(10);
JTextField totalTaxField = new JTextField(10);
JTextField netSalesField = new JTextField(10);
JTextField dailyCostField = new JTextField(10);
JTextField profitField = new JTextField(10);
JButton clearButton = new JButton("Clear Fields");// Creating buttons
JButton calculateButton = new JButton("Calculate");
JButton exitButton = new JButton("Exit");
JPanel subPanel1 = new JPanel();
JPanel subPanel2 = new JPanel();
JPanel subPanel3 = new JPanel();
JPanel top = new JPanel();
public class GUI extends JPanel {
public GUI() {
subPanel1.setLayout(new GridLayout(4, 2));
subPanel1.add(lPizzaLabel);
subPanel1.add(largeField);
subPanel1.add(mPizzaLabel);
subPanel1.add(mediumField);
subPanel1.add(sPizzaLabel);
subPanel1.add(smallField);
subPanel1.add(bSticksLabel);
subPanel1.add(breadField);
subPanel1.setBorder(BorderFactory.createTitledBorder("Panel 1"));
// subPanel2.setLayout(new BoxLayout(subPanel2, BoxLayout.Y_AXIS)); // Same as next line
subPanel2.setLayout(new GridLayout(4, 1));
subPanel2.add(totalLargeField);
subPanel2.add(totalMediumField);
subPanel2.add(totalSmallField);
subPanel2.add(totalBreadField);
subPanel2.setBorder(BorderFactory.createTitledBorder("Panel 2"));
subPanel3.setLayout(new GridLayout(5, 2));
subPanel3.add(totalSalesLabel);
subPanel3.add(totalSalesField);
subPanel3.add(totalTaxLabel);
subPanel3.add(totalTaxField);
subPanel3.add(netSalesLabel);
subPanel3.add(netSalesField);
subPanel3.add(dailyCostLabel);
subPanel3.add(dailyCostField);
subPanel3.add(profitLabel);
subPanel3.add(profitField);
JLabel title = new JLabel("Eve's Pizza Daily Sales");
title.setFont(new Font("Helvetica", 1, 14));
top.add(title);
top.setBackground(Color.YELLOW);
totalSalesField.setEditable(false);// making total field uneditable
totalTaxField.setEditable(false);
netSalesField.setEditable(false);
dailyCostField.setEditable(false);
profitField.setEditable(false);
}
}
public DailySales() // creating a constructor
{
/**
* The constructor with all the layout informations and operators Also
* adding all labels, textfields, and buttons to frame. making the total
* field uneditable
*/
new GUI();
JPanel mainPanel = new JPanel(new GridLayout(2, 2));
mainPanel.add(subPanel1);
mainPanel.add(subPanel2);
mainPanel.add(subPanel3);
JPanel buttonPanel = new JPanel();
buttonPanel.add(clearButton);
buttonPanel.add(calculateButton);
buttonPanel.add(exitButton);
JFrame frame = new JFrame();
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(top, BorderLayout.PAGE_START);
frame.getContentPane().add(mainPanel, BorderLayout.CENTER);
frame.getContentPane().add(buttonPanel, BorderLayout.PAGE_END);
frame.setSize(600, 450);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
clearButton.addActionListener(new ActionListener() {// initial button
// removes all
// entered text
public void actionPerformed(ActionEvent e) {
largeField.setText("");
mediumField.setText("");
smallField.setText("");
breadField.setText("");
totalLargeField.setText("");
totalMediumField.setText("");
totalSmallField.setText("");
totalBreadField.setText("");
totalSalesField.setText("");
totalTaxField.setText("");
netSalesField.setText("");
dailyCostField.setText("");
profitField.setText("");
}
});
calculateButton.addActionListener(new ActionListener() {// update button
// calculates
// all the
// inputs and
// displays
// everything
public void actionPerformed(ActionEvent e) {
lPizza = largeField.getText();
mPizza = mediumField.getText();
sPizza = smallField.getText();
bSticks = breadField.getText();
largePizza = Integer.parseInt(lPizza);
mediumPizza = Integer.parseInt(mPizza);
smallPizza = Integer.parseInt(sPizza);
breadSticks = Integer.parseInt(bSticks);
totalLargePizza = (lPizzaPrice*largePizza);
totalMediumPizza = (mPizzaPrice*mediumPizza);
totalSmallPizza = (sPizzaPrice*smallPizza);
totalBreadSticks = (bSticksPrice*breadSticks);
totalLargeField.setText(""+totalLargePizza);
totalMediumField.setText(""+totalMediumPizza);
totalSmallField.setText(""+totalSmallPizza);
totalBreadField.setText(""+totalBreadSticks);
totalSales = (totalLargePizza+totalMediumPizza+totalSmallPizza+totalBreadSticks);
totalTax = (totalSales*tax);
netSales = (totalSales-totalTax);
profit = (netSales-dailyOper);
/**
* calculates total by adding all entered values if else
* statements for different situations that calculate the
* different between total and diet
*/
if (profit>0) {
profitLabel.setText("Profit of ");
} else if (profit<0) {
profitLabel.setText("Loss of ");
} else if (profit==0) {
profitLabel.setText("No profit or loss ");
}
if (largePizza<0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (mediumPizza<0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (smallPizza<0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
} else if (breadSticks<0) {
JOptionPane.showMessageDialog(null, "Quantity muist be >=0");
}
}
});
exitButton.addActionListener(new ActionListener() {// close button
// closes the
// program when
// clicked on
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
new DailySales();
}
}
I have a half complete coding which basically comes down to a gui interface. The problem is that I don't know how to get it working as ticket vending machine with fixed rates and fixed amount of cash being able to put in.
So, far, I've done up to calculating total where nomatter what I do, it always comes up with a £0.00 as the totalamount answer.
I am in desperate need of help. This is very frustrating. Below is the code for the TicketCalculation Class
import java.awt.*;
import java.text.*;
import java.awt.event.*;
import javax.swing.*;
public class TicketCalculation extends JFrame implements ActionListener {
DecimalFormat pounds = new DecimalFormat("£#,##0.00");
//creating and naming buttons and textfields
private JButton twentypenceBtn = new JButton("20p");
private JButton fiftypenceBtn = new JButton("50p");
private JButton onepoundBtn = new JButton("£1");
private JButton twopoundsBtn = new JButton("£2");
private JButton fivepoundsBtn = new JButton("£5");
private JButton tenpoundsBtn = new JButton("£10");
private JButton twentypoundsBtn = new JButton("£20");
private JButton C = new JButton("Calculate");
private JButton frontBtn = new JButton("<<Front Stalls>>");
private JButton private1Btn = new JButton("<<Private Box>>");
private JButton middleBtn = new JButton("<<Middle Stalls>>");
private JButton backBtn = new JButton("<<Back Stalls>>");
private JButton calcBtn = new JButton("Calculate Bill");
private JTextField tickettypeTxt = new JTextField(14);
private JTextField stalltypeTxt = new JTextField(25);
private JTextField amountticketsTxt = new JTextField(14);
private JTextField totalamountTxt = new JTextField(10);
private JTextField amountdueTxt = new JTextField(13);
private JTextField amountpaidTxt = new JTextField(10);
//creating labels
private JLabel pickstall = new JLabel();
private JLabel tictype = new JLabel ();
private JLabel amontic = new JLabel();
private JLabel ttamon = new JLabel();
private JLabel amondue = new JLabel();
private JLabel amonpaid = new JLabel();
private JLabel label5 = new JLabel();
private JLabel spacing6 = new JLabel();
private JLabel spacing7 = new JLabel();
private JLabel spacing8 = new JLabel();
private JLabel spacing9 = new JLabel();
private JLabel spacing10 = new JLabel();
//image icon declarations
private ImageIcon paycount = new ImageIcon(getClass().getResource("paycount.jpg"));
double middleprice;
double privateprice;
double backprice;
double frontprice;
double type;
int number;
public static void main(String[] args){
new TicketCalculation();
}
public TicketCalculationt(){
setLayout(new BorderLayout());
setSize(650,750);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//naming labels
pickstall = new JLabel("==> Pick a Stall Type: ");
tictype = new JLabel ("==> Price of a Ticket: £");
amontic = new JLabel("==> Amount of Tickets: ");
ttamon = new JLabel("==> Total Amount: ");
amondue = new JLabel("==> Amount Due: £");
amonpaid = new JLabel("==> Amount Paid: £");
label5 = new JLabel(paycount);
spacing6 = new JLabel(" ");
spacing7 = new JLabel(" ");
spacing8 = new JLabel(" ");
spacing9 = new JLabel(" ");
spacing10 = new JLabel(" ");
//setting font for buttons, textfields and labels
pickstall.setFont(new Font("Rockwell", Font.BOLD, 20));
frontBtn.setFont(new Font("System", Font.BOLD, 22));
middleBtn.setFont(new Font("System", Font.BOLD, 22));
backBtn.setFont(new Font("System", Font.BOLD, 22));
private1Btn.setFont(new Font("System", Font.BOLD, 22));
tictype.setFont(new Font("Rockwell", Font.BOLD, 20));
amontic.setFont(new Font("Rockwell", Font.BOLD, 20));
ttamon.setFont(new Font("Rockwell", Font.BOLD, 20));
amondue.setFont(new Font("Rockwell", Font.BOLD, 20));
amonpaid.setFont(new Font("Rockwell", Font.BOLD, 20));
stalltypeTxt.setFont(new Font("Verdana", Font.BOLD, 20));
tickettypeTxt.setFont(new Font("Verdana", Font.BOLD, 20));
amountticketsTxt.setFont(new Font("Verdana", Font.BOLD, 20));
totalamountTxt.setFont(new Font("Verdana", Font.BOLD, 20));
amountdueTxt.setFont(new Font("Verdana", Font.BOLD, 20));
amountpaidTxt.setFont(new Font("Verdana", Font.BOLD, 20));
twentypenceBtn.setFont(new Font("Century Gothic", Font.BOLD, 28));
fiftypenceBtn.setFont(new Font("Century Gothic", Font.BOLD, 28));
onepoundBtn.setFont(new Font("Century Gothic", Font.BOLD, 28));
twopoundsBtn.setFont(new Font("Century Gothic", Font.BOLD, 28));
fivepoundsBtn.setFont(new Font("Century Gothic", Font.BOLD, 28));
tenpoundsBtn.setFont(new Font("Century Gothic", Font.BOLD, 28));
twentypoundsBtn.setFont(new Font("Century Gothic", Font.BOLD, 28));
C.setFont(new Font("Serif", Font.BOLD, 28));
stalltypeTxt.setEditable(false);
tickettypeTxt.setEditable(false);
totalamountTxt.setEditable(false);
amountdueTxt.setEditable(false);
amountpaidTxt.setEditable(false);
//positioning all buttons, textfields and labels
JPanel top = new JPanel();
top.add(label5);
add("North", top);
JPanel mid = new JPanel();
mid.add(pickstall);
mid.add(stalltypeTxt);
mid.add(spacing6);
mid.add(private1Btn);
mid.add(frontBtn);
mid.add(middleBtn);
mid.add(backBtn);
mid.add(tictype);
mid.add(tickettypeTxt);
mid.add(spacing7);
mid.add(amontic);
mid.add(amountticketsTxt);
mid.add(spacing8);
mid.add(ttamon);
mid.add(totalamountTxt);
mid.add(calcBtn);
mid.add(spacing10);
mid.add(amonpaid);
mid.add(amountpaidTxt);
mid.add(spacing9);
mid.add(twentypenceBtn);
mid.add(fiftypenceBtn);
mid.add(onepoundBtn);
mid.add(twopoundsBtn);
mid.add(fivepoundsBtn);
mid.add(tenpoundsBtn);
mid.add(twentypoundsBtn);
mid.add(amondue);
mid.add(amountdueTxt);
mid.add(C);
add("Center", mid);
calcBtn.addActionListener(this);
private1Btn.addActionListener(this);
frontBtn.addActionListener(this);
middleBtn.addActionListener(this);
backBtn.addActionListener(this);
twentypenceBtn.addActionListener(this);
fiftypenceBtn.addActionListener(this);
onepoundBtn.addActionListener(this);
twopoundsBtn.addActionListener(this);
fivepoundsBtn.addActionListener(this);
tenpoundsBtn.addActionListener(this);
twentypoundsBtn.addActionListener(this);
C.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
// event handler for the buttons
if (e.getSource() == private1Btn)
{
stalltypeTxt.setText("Private Stall Location is Chosen");
tickettypeTxt.setText("30.85");
}
else if (e.getSource() == frontBtn)
{
stalltypeTxt.setText("Front Stall Location is Chosen");
tickettypeTxt.setText("15.00");
}
else if (e.getSource() == middleBtn)
{
stalltypeTxt.setText("Middle Stall Location is Chosen");
tickettypeTxt.setText("10.20");
}
else if (e.getSource() == backBtn)
{
stalltypeTxt.setText("Back Stall Location is Chosen");
tickettypeTxt.setText("5.70");
}
else if (e.getSource() == tickettypeTxt)
{
type = Double.parseDouble(tickettypeTxt.getText());
}
else if (e.getSource() == amountticketsTxt)
{
number = Integer.parseInt(amountticketsTxt.getText());
}
else if (e.getSource() == calcBtn)
{
Workings c = new Workings();
w.setType(type);
w.setNumber(number);
double total = w.calculateBill();
totalamountTxt.setText(pounds.format(total));
}
}
}
with a halfway done auxiliary class called Workings
public class Workings {
// private instance variables
private double type, number;
// public no-argument constructor
public Workings() { }
// public constructor with four arguments
public Workings(double t, int n)
{
type = t;
number = n;
}
// public 'set' methods
public void setType(double t) { type = t; }
public void setNumber(int n) { number = n; }
// public method to calculate the bill
public double calculateBill()
{
double total = type * number ;
return total;
}
}
The ActionListener is only triggered on a JTextField when the user hits the Enter key on the keyboard while in that field. This is unintuitive, so I would say it's a big no-no to use ActionListener for that.
Instead, use a FocusListener to get the "user left the text field" events from the text fields. That should pick up the data entered and then it should work.
Here's your problem
else if (e.getSource() == tickettypeTxt)
{
type = Double.parseDouble(tickettypeTxt.getText());
}
else if (e.getSource() == amountticketsTxt)
{
number = Integer.parseInt(amountticketsTxt.getText());
}
else if (e.getSource() == calcBtn)
{
Workings c = new Workings();
w.setType(type);
w.setNumber(number);
double total = w.calculateBill();
totalamountTxt.setText(pounds.format(total));
}
Delete the first two else ifs and just do this
else if (e.getSource() == calcBtn)
{
type = Double.parseDouble(tickettypeTxt.getText());
number = Integer.parseInt(amountticketsTxt.getText());
Workings c = new Workings();
w.setType(type);
w.setNumber(number);
double total = w.calculateBill();
totalamountTxt.setText(pounds.format(total));
}
I am having a lot of issues with this application. I have been at this all day and cannot get this figured out. I have a Java application that is for a class. The issue that I am having is trying to get the JRadioButtons assigned to variables in the array then passing them into the formula. If someone could help I would appreciate it a lot.
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.text.NumberFormat;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.JRadioButton;
public class MortgageCalculatorGUI8 extends JFrame {
JPanel panel1 = new JPanel();
double Principal;
double [] Interest = {5.35, 5.5, 5.75};
double temp_Interest;
int [] Length = {7, 15, 30};
int temp_Length;
boolean ok = false;
public MortgageCalculatorGUI8(){
getContentPane ().setLayout (null);
setSize (400,400);
panel1.setLayout (null);
panel1.setBounds (0, 0, 2000, 800);
add (panel1);
JLabel mortgageLabel = new JLabel("Mortgage Amount $", JLabel.LEFT);
mortgageLabel.setBounds (15, 15, 150, 30);
panel1.add (mortgageLabel);
final JTextField mortgageText = new JTextField(10);
mortgageText.setBounds (130, 15, 150, 30);
panel1.add (mortgageText);
JLabel termLabel = new JLabel("Mortgage Term (Years)", JLabel.LEFT);
termLabel.setBounds (340, 40, 150, 30);
panel1.add (termLabel);
JTextField termText = new JTextField(3);
termText.setBounds (340, 70, 150, 30);
panel1.add (termText);
JLabel intRateLabel = new JLabel("Interest Rate (%)", JLabel.LEFT);
intRateLabel.setBounds (340, 94, 150, 30);
panel1.add (intRateLabel);
JTextField intRateText = new JTextField(5);
intRateText.setBounds (340, 120, 150, 30);
panel1.add (intRateText);
JLabel mPaymentLabel = new JLabel("Monthly Payment $", JLabel.LEFT);
mPaymentLabel.setBounds (550, 40, 150, 30);
panel1.add (mPaymentLabel);
JTextField mPaymentText = new JTextField(10);
mPaymentText.setBounds (550, 70, 150, 30);
panel1.add (mPaymentText);
// JLabel paymentLabel = new JLabel ("Payment #");
// JLabel balLabel = new JLabel (" Balance");
// JLabel ytdPrincLabel = new JLabel (" Principal");
// JLabel ytdIntLabel = new JLabel (" Interest");
JTextArea textArea = new JTextArea(10, 31);
textArea.setBounds (550, 100, 150, 30);
panel1.add (textArea);
JScrollPane scroll = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scroll.setBounds (450, 200, 300, 150);
panel1.add (scroll);
public void rbuttons(){
JLabel tYears = new JLabel("Years of Loan Amount");
tYears.setBounds (30, 35, 150, 30);
panel1.add (tYears);
JRadioButton b7Yr = new JRadioButton("7 Years",false);
b7Yr.setBounds (30, 58, 150, 30);
panel1.add (b7Yr);
JRadioButton b15Yr = new JRadioButton("15 Years",false);
b15Yr.setBounds (30, 80, 150, 30);
panel1.add (b15Yr);
JRadioButton b30Yr = new JRadioButton("30 Years",false);
b30Yr.setBounds (30, 101, 150, 30);
panel1.add (b30Yr);
JLabel tInterest = new JLabel("Interest Rate Of the Loan");
tInterest.setBounds (175, 35, 150, 30);
panel1.add(tInterest);
JRadioButton b535Int = new JRadioButton("5.35% Interest",false);
b535Int.setBounds (178, 58, 150, 30);
panel1.add (b535Int);
JRadioButton b55Int = new JRadioButton("5.5% Interest",false);
b55Int.setBounds (178, 80, 150, 30);
panel1.add (b55Int);
JRadioButton b575Int = new JRadioButton("5.75% Interest",false);
b575Int.setBounds (178, 101, 150, 30);
panel1.add (b575Int);
}
JButton calculateButton = new JButton("CALCULATE");
calculateButton.setBounds (30, 400, 120, 30);
panel1.add (calculateButton);
calculateButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
if(e.getSource () == b7Yr){
b7Yr = Length[0];
}
if(e.getSource () == b15Yr){
b15Yr = Length[1];
}
if(e.getSource () == b30Yr){
b30Yr = Length[2];
}
if(e.getSource () == b535Int){
b535Int = Interest[0];
}
if(e.getSource () == b55Int){
b55Int = Interest[1];
}
if(e.getSource () == b575Int){
b575Int = Interest[2];
}
double Principal;
// double [] Interest;
// int [] Length;
double M_Interest = Interest /(12*100);
double Months = Length * 12;
Principal = Double.parseDouble (mortgageText.getText());
double M_Payment = Principal * ( M_Interest / (1 - (Math.pow((1 + M_Interest), - Months))));
NumberFormat Money = NumberFormat.getCurrencyInstance();
}
});
JButton clearButton = new JButton("CLEAR");
clearButton.setBounds (160, 400, 120, 30);
panel1.add (clearButton);
clearButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
mortgageText.setText (null);
b7Yr.setSelected (false);
b15Yr.setSelected (false);
b30Yr.setSelected (false);
b535Int.setSelected (false);
b55Int.setSelected (false);
b575Int.setSelected (false);
}
});
JButton exitButton = new JButton("EXIT");
exitButton.setBounds (290, 400, 120, 30);
panel1.add (exitButton);
exitButton.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
}
public static void main(String[] args) {
MortgageCalculatorGUI8 frame = new MortgageCalculatorGUI8();
frame.setBounds (400, 200, 800, 800);
frame.setTitle ("Mortgage Calculator 1.0.4");
frame.setDefaultCloseOperation (EXIT_ON_CLOSE);
frame.setVisible (true);
}
}
Shoot, I'll show you in an example of what I meant in my last comment:
Myself, I'd create an array of JRadioButtons as a class field for each group that I used as well as a ButtonGroup object for each cluster of JRadioButtons. Then in my calculate JButton's ActionListener, I'd get the selected radiobutton by either looping through the radio button array or from the ButtonGroups getSelection method (note though that this returns a ButtonModel object or null if nothing is selected).
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class InfoFromRadioBtns extends JPanel {
private static final long serialVersionUID = 1L;
private int[] foobars = {1, 2, 5, 10, 20};
private JRadioButton[] foobarRButtons = new JRadioButton[foobars.length];
private ButtonGroup foobarBtnGroup = new ButtonGroup();
public InfoFromRadioBtns() {
// jpanel to hold one set of radio buttons
JPanel radioBtnPanel = new JPanel(new GridLayout(0, 1));
radioBtnPanel.setBorder(BorderFactory
.createTitledBorder("Choose a Foobar"));
// iterate through the radio button array creating buttons
// and adding them to the radioBtnPanel and the
// foobarBtnGroup ButtonGroup
for (int i = 0; i < foobarRButtons.length; i++) {
// string for radiobutton to dislay -- just the number
String buttonText = String.valueOf(foobars[i]);
JRadioButton radiobtn = new JRadioButton("foobar " + buttonText);
radiobtn.setActionCommand(buttonText); // one way to find out which
// button is selected
radioBtnPanel.add(radiobtn); // add radiobutton to its panel
foobarBtnGroup.add(radiobtn); // add radiobutton to its button group
// add to array
foobarRButtons[i] = radiobtn;
}
// one way to get the selected JRadioButton
JButton getRadioChoice1 = new JButton("Get Radio Choice 1");
getRadioChoice1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ButtonModel seletedModel = foobarBtnGroup.getSelection();
if (seletedModel != null) {
String actionCommand = seletedModel.getActionCommand();
System.out.println("selected foobar: " + actionCommand);
} else {
System.out.println("No foobar selected");
}
}
});
// another way to get the selected JRadioButton
JButton getRadioChoice2 = new JButton("Get Radio Choice 2");
getRadioChoice2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String actionCommand = "";
for (JRadioButton foobarRButton : foobarRButtons) {
if (foobarRButton.isSelected()) {
actionCommand = foobarRButton.getActionCommand();
}
}
if (actionCommand.isEmpty()) {
System.out.println("No foobar selected");
} else {
System.out.println("selected foobar: " + actionCommand);
}
}
});
JPanel jBtnPanel = new JPanel();
jBtnPanel.add(getRadioChoice1);
jBtnPanel.add(getRadioChoice2);
// make main GUI use a BordeLayout
setLayout(new BorderLayout());
add(radioBtnPanel, BorderLayout.CENTER);
add(jBtnPanel, BorderLayout.PAGE_END);
}
private static void createAndShowUI() {
JFrame frame = new JFrame("InfoFromRadioBtns");
frame.getContentPane().add(new InfoFromRadioBtns());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
createAndShowUI();
}
});
}
}
Whatever you do, don't try to copy and paste any of this code into your program, because it simply isn't going to work that way (on purpose). It was posted only to illustrate the concepts that I've discussed above.
I would extend JRadioButton to create a class capable of holding the variables you want. You can do this as an inner class to keep things simple.
private double pctinterest;
private int numyears; // within scope of your containing class
private class RadioButtonWithYears extends JRadioButton {
final private int years;
private int getYears() { return years; }
public RadioButtonWithYears(int years) {
super(years + " years",false);
this.years = years;
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
numyears = getYears();
}
});
}
}
// elsewhere
RadioButtonWithYears b7Yr = new RadioButtonWithYears(7);
RadioButtonWithYears b15Yr = new RadioButtonWithYears(15);
RadioButtonWithYears b30Yr = new RadioButtonWithYears(30);
// then later
double M_Interest = java.lang.Math.pow((pctinternet / 100)+1, numyears);
Update: It isn't too far gone to salvage. I have incorporated the ButtonGroup as per Eels suggestion, and made the GUI part of it work (although you'll have to fix the layout) and marked where you need to sort out the calculation.
package stack.swing;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.math.BigDecimal;
import java.text.NumberFormat;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.JRadioButton;
public class MortgageCalculatorGUI8 extends JFrame {
JPanel panel1 = new JPanel();
Integer Principal;
boolean ok = false;
private BigDecimal temp_Interest;
private int temp_Length; // within scope of your containing class
private class JRadioButtonWithYears extends JRadioButton {
final private int years;
private int getYears() { return years; }
public JRadioButtonWithYears(int years) {
super(years + " years",false);
this.years = years;
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
temp_Length = getYears();
}
});
}
}
private class JRadioButtonWithPct extends JRadioButton {
final private BigDecimal pct;
private BigDecimal getPct() { return pct; }
public JRadioButtonWithPct(String pct) {
super(pct + "%",false);
this.pct = new BigDecimal(pct);
addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
temp_Interest = getPct();
}
});
}
}
public MortgageCalculatorGUI8() {
getContentPane ().setLayout (null);
setSize (400,400);
panel1.setLayout (null);
panel1.setBounds (0, 0, 2000, 800);
add (panel1);
JLabel mortgageLabel = new JLabel("Mortgage Amount $", JLabel.LEFT);
mortgageLabel.setBounds (15, 15, 150, 30);
panel1.add (mortgageLabel);
final JTextField mortgageText = new JTextField(10);
mortgageText.setBounds (130, 15, 150, 30);
panel1.add (mortgageText);
JLabel termLabel = new JLabel("Mortgage Term (Years)", JLabel.LEFT);
termLabel.setBounds (340, 40, 150, 30);
panel1.add (termLabel);
JTextField termText = new JTextField(3);
termText.setBounds (340, 70, 150, 30);
panel1.add (termText);
JLabel intRateLabel = new JLabel("Interest Rate (%)", JLabel.LEFT);
intRateLabel.setBounds (340, 94, 150, 30);
panel1.add (intRateLabel);
JTextField intRateText = new JTextField(5);
intRateText.setBounds (340, 120, 150, 30);
panel1.add (intRateText);
JLabel mPaymentLabel = new JLabel("Monthly Payment $", JLabel.LEFT);
mPaymentLabel.setBounds (550, 40, 150, 30);
panel1.add (mPaymentLabel);
JTextField mPaymentText = new JTextField(10);
mPaymentText.setBounds (550, 70, 150, 30);
panel1.add (mPaymentText);
// JLabel paymentLabel = new JLabel ("Payment #");
// JLabel balLabel = new JLabel (" Balance");
// JLabel ytdPrincLabel = new JLabel (" Principal");
// JLabel ytdIntLabel = new JLabel (" Interest");
JTextArea textArea = new JTextArea(10, 31);
textArea.setBounds (550, 100, 150, 30);
panel1.add (textArea);
JScrollPane scroll = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
scroll.setBounds (450, 200, 300, 150);
panel1.add (scroll);
// jpanel to hold one set of radio buttons
JPanel yearsPanel = new JPanel(new GridLayout(0, 1));
yearsPanel.setBorder(BorderFactory
.createTitledBorder("Years of Loan Amount"));
yearsPanel.setBounds(30, 55, 150, 150);
panel1.add (yearsPanel);
final ButtonGroup yearsGroup = new ButtonGroup();
int years[] = { 7, 15, 30 };
for (int i = 0; i < years.length; i++) {
JRadioButtonWithYears radiobtn = new JRadioButtonWithYears(years[i]);
yearsPanel.add(radiobtn); // add radiobutton to its panel
yearsGroup.add(radiobtn); // add radiobutton to its button group
}
// jpanel to hold one set of radio buttons
JPanel pctPanel = new JPanel(new GridLayout(0, 1));
pctPanel.setBorder(BorderFactory
.createTitledBorder("Interest Rate Of the Loan"));
pctPanel.setBounds(175, 55, 180, 150);
panel1.add (pctPanel);
final ButtonGroup pctGroup = new ButtonGroup();
String pct[] = { "5.35", "5.5", "5.75" };
for (int i = 0; i < pct.length; i++) {
JRadioButtonWithPct radiobtn = new JRadioButtonWithPct(pct[i]);
pctPanel.add(radiobtn); // add radiobutton to its panel
pctGroup.add(radiobtn); // add radiobutton to its button group
}
final JButton calculateButton = new JButton("CALCULATE");
calculateButton.setBounds (30, 400, 120, 30);
panel1.add (calculateButton);
calculateButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double M_Interest = temp_Interest.doubleValue() /(12*100);
double Months = temp_Length * 12;
Principal = Integer.parseInt(mortgageText.getText());
double M_Payment = Principal * ( M_Interest / (1 - (Math.pow((1 + M_Interest), - Months))));
NumberFormat Money = NumberFormat.getCurrencyInstance();
/** MORE STUFF TO HAPPEN HERE */
}
});
JButton clearButton = new JButton("CLEAR");
clearButton.setBounds (160, 400, 120, 30);
panel1.add (clearButton);
clearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
mortgageText.setText (null);
yearsGroup.clearSelection();
pctGroup.clearSelection();
}
});
JButton exitButton = new JButton("EXIT");
exitButton.setBounds (290, 400, 120, 30);
panel1.add (exitButton);
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
}
public static void main(String[] args) {
MortgageCalculatorGUI8 frame = new MortgageCalculatorGUI8();
frame.setBounds (400, 200, 800, 800);
frame.setTitle ("Mortgage Calculator 1.0.4");
frame.setDefaultCloseOperation (EXIT_ON_CLOSE);
frame.setVisible (true);
}
}