Getting methods to print to a TextArea in JPanel - java

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.

Related

JTextArea Displays 0 after calculate button clicked

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();
}
}

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException at GratuityCalculator.getGratuity(GratuityCalculator.java:188)

Ok this is my first multi-class program... The output needs to be in a currency format but when I try I get the error(Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at GratuityCalculator.getGratuity(GratuityCalculator.java:186)
So I know where the error is but cant figure out why.
here is the code that throws the error its line 186 if I use the currency.format code I get an error if not no error but no currency either:
public class GratuityCalculator extends JFrame
{
/* declarations */
// color objects
Color black = new Color(0, 0, 0);
Color white = new Color(255, 255, 255);
DecimalFormat currency;
//components
JLabel billAmountJLabel;
JTextField billAmountJTextField;
JLabel gratuityJLabel;
JTextField gratuityJTextField;
JButton enterJButton;
JButton clearJButton;
JButton closeJButton;
// variables
double billAmount;
final double GRATUITY_RATE = .15;
double gratuityAmount;
// objects
CalculateTip calculateTip;// object class
public GratuityCalculator()
{
createUserInterface();
}
public void createUserInterface()
{
Container contentPane = getContentPane();
contentPane.setBackground (Color.white);
contentPane.setLayout(null);
//initialize components
billAmountJLabel = new JLabel();
billAmountJLabel.setBounds(50, 50, 120, 20);
billAmountJLabel.setFont(new Font("Default", Font.PLAIN, 12));
billAmountJLabel.setText("Enter bill amount");
billAmountJLabel.setForeground(black);
billAmountJLabel.setHorizontalAlignment(JLabel.LEFT);
contentPane.add(billAmountJLabel);
billAmountJTextField = new JTextField();
billAmountJTextField.setBounds(225, 50, 50, 20);
billAmountJTextField.setFont(new Font("Default", Font.PLAIN, 12));
billAmountJTextField.setHorizontalAlignment(JTextField.CENTER);
billAmountJTextField.setForeground(black);
billAmountJTextField.setBackground(white);
billAmountJTextField.setEditable(true);
contentPane.add(billAmountJTextField);
gratuityJLabel = new JLabel();
gratuityJLabel.setBounds(50, 80, 150, 20);
gratuityJLabel.setFont(new Font("Default", Font.PLAIN, 12));
gratuityJLabel.setText("Gratuity");
gratuityJLabel.setForeground(black);
gratuityJLabel.setHorizontalAlignment(JLabel.LEFT);
contentPane.add(gratuityJLabel);
gratuityJTextField = new JTextField();
gratuityJTextField.setBounds(225, 80, 50, 20);
gratuityJTextField.setFont(new Font("Default", Font.PLAIN, 12));
gratuityJTextField.setHorizontalAlignment(JTextField.CENTER);
gratuityJTextField.setForeground(black);
gratuityJTextField.setBackground(white);
gratuityJTextField.setEditable(false);
contentPane.add(gratuityJTextField);
enterJButton = new JButton();
enterJButton.setBounds(20, 300, 100, 20);
enterJButton.setFont(new Font("Default", Font.PLAIN, 12));
enterJButton.setText("Enter");
enterJButton.setForeground(black);
enterJButton.setBackground(white);
contentPane.add(enterJButton);
enterJButton.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
enterJButtonActionPerformed(event);
}
}
);
clearJButton = new JButton();
clearJButton.setBounds(140, 300, 100, 20);
clearJButton.setFont(new Font("Default", Font.PLAIN, 12));
clearJButton.setText("Clear");
clearJButton.setForeground(black);
clearJButton.setBackground(white);
contentPane.add(clearJButton);
clearJButton.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
clearJButtonActionPerformed(event);
}
}
);
closeJButton = new JButton();
closeJButton.setBounds(260, 300, 100, 20);
closeJButton.setFont(new Font("Default", Font.PLAIN, 12));
closeJButton.setText("Close");
closeJButton.setForeground(black);
closeJButton.setBackground(white);
contentPane.add(closeJButton);
closeJButton.addActionListener(
new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
closeJButtonActionPerformed(event);
}
}
);
setTitle("Gratuity Calculator");
setSize( 400, 400 );
setVisible(true);
}
//main method
public static void main(String[] args)
{
GratuityCalculator application = new GratuityCalculator();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void enterJButtonActionPerformed(ActionEvent event)
{
getBillAmount();
}
public void getBillAmount()
{
try
{
billAmount = Double.parseDouble(billAmountJTextField.getText());
getGratuity();
}
catch(NumberFormatException exception)
{
JOptionPane.showMessageDialog(this,
"Please Enter Bill Amount!",
"Number Format Error", JOptionPane.ERROR_MESSAGE);
billAmountJTextField.setText("");
billAmountJTextField.requestFocusInWindow();
}
}
public void getGratuity()
{
/*
Object class is created and gratuity calculated
*/
calculateTip = new CalculateTip(billAmount, GRATUITY_RATE);
/*
Call object class
*/
gratuityAmount = calculateTip.getGratuity();
gratuityJTextField.setText("" + currency.format(gratuityAmount));
}
public void clearJButtonActionPerformed(ActionEvent event)
{
billAmountJTextField.setText("");
billAmountJTextField.requestFocusInWindow();
gratuityJTextField.setText("");
}
public void closeJButtonActionPerformed(ActionEvent event)
{
GratuityCalculator.this.dispose();
}
}
class CalculateTip
{
// class variables
double firstNumber;
double secondNumber;
/*
The object class constructor receives the two values
from the interface class and the two parameter values
are assigned to the class variables
*/
public CalculateTip(double billAmount, double GRATUITY_RATE)
{
firstNumber = billAmount;
secondNumber = GRATUITY_RATE;
}
/*
This method returns the sum of the values to the class
*/
public double getGratuity()
{
return firstNumber * secondNumber;
}
}
Any help appreciated. let me know if more info is required.

Ticket vending machine

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));
}

Having trouble understanding JList

I've built a program (which runs fine), but I really wanted to use JList instead of radio buttons. The problem is, I'm having a horrible time trying to do this and I end up with a mess of errors and a dysfunctional program. If anyone could provide any examples of how lists are properly used in Java, it would be greatly appreciated! I've not posted my program, as I'm not looking for answers, just general advice on JList. Thanks for those who have suggested the tutorial link - it helped out! :)
If anyone could provide any examples of how lists are properly used in Java
Read the JList API and follow the link titled How to Use Lists to the Swing tutorial which contains working examples.
Other comments:
Don't use setBounds() to size/position components. Swing was designed to be used with layout managers for too many reasons to list here. The Swing tutorial also has a section on layout managers.
Don't use a KeyListner. That is an old approach when using AWT. Swing has better API's. In this case you would add a DocumentListener to the Document of the text field. Again the tutorial has a section on how to write a DocumentListener.
Keep the tutorial link handy, it will help solve many problems.
I have done something with your code have look
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
public class PizzaOrder extends JFrame implements ActionListener, KeyListener, ListSelectionListener {
double smallPizzaPrice = 7.00, mediumPizzaPrice = 9.00,
largePizzaPrice = 11.00;
double sausage = 1.00, ham = 1.00, pineapple = 1.00, mushroom = 1.00,
pepperoni = 1.00;
JLabel lab1, lab2, lab3, toppers, lab4, lab5;
Button button;
JTextField text1, text2;
ButtonGroup group;
JRadioButton small, medium, large;
JCheckBox chk1, chk2, chk3, chk4, chk5;
JScrollPane jScrollPane1 = new javax.swing.JScrollPane();
JList jList1 = new javax.swing.JList();
DefaultListModel modellist=new DefaultListModel();
PizzaOrder() {
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
lab1 = new JLabel("Name: ");
lab2 = new JLabel("Quantity: ");
lab3 = new JLabel("How hungry are you?");
lab3.setForeground(Color.BLUE);
lab3.setFont(new Font("Arial", Font.BOLD, 14));
toppers = new JLabel("Add some toppings : ");
toppers.setForeground(new Color(0, 0, 205));
toppers.setFont(new Font("Arial", Font.ITALIC, 14));
lab4 = new JLabel("Total: ");
lab4.setForeground(Color.RED);
lab4.setFont(new Font("Arial", Font.BOLD, 14));
lab5 = new JLabel("$0.00");
lab5.setForeground(Color.RED);
text1 = new JTextField(20);
text2 = new JTextField(20);
text2.setText("");
small = new JRadioButton("Small", true);
medium = new JRadioButton("Medium", false);
large = new JRadioButton("Large", false);
group = new ButtonGroup();
group.add(small);
group.add(medium);
group.add(large);
chk1 = new JCheckBox("Mushroom", false);
chk2 = new JCheckBox("Ham", false);
chk3 = new JCheckBox("Pepperoni", false);
chk4 = new JCheckBox("Sausage", false);
chk5 = new JCheckBox("Pineapple", false);
modellist.addElement("Small");
modellist.addElement("Medium");
modellist.addElement("Large");
jList1.setModel(modellist);
button = new Button("Order Now");
small.addActionListener(this);
medium.addActionListener(this);
large.addActionListener(this);
chk1.addActionListener(this);
chk2.addActionListener(this);
chk3.addActionListener(this);
chk4.addActionListener(this);
chk5.addActionListener(this);
text2.addKeyListener(this);
button.addActionListener(this);
jList1.addListSelectionListener(this);
lab1.setBounds(50, 50, 200, 20);
lab2.setBounds(50, 90, 200, 20);
text1.setBounds(200, 50, 200, 20);
text2.setBounds(200, 90, 200, 20);
lab3.setBounds(50, 170, 500, 20);
small.setBounds(300, 170, 100, 20);
medium.setBounds(400, 170, 100, 20);
large.setBounds(500, 170, 100, 20);
toppers.setBounds(50, 200, 300, 20);
chk1.setBounds(50, 230, 200, 20);
chk2.setBounds(50, 260, 200, 20);
chk3.setBounds(50, 290, 200, 20);
chk4.setBounds(50, 320, 200, 20);
chk5.setBounds(50, 350, 200, 20);
lab4.setBounds(50, 550, 400, 40);
lab5.setBounds(200, 550, 500, 40);
jScrollPane1.setBounds(300, 270, 200, 300);
jScrollPane1.setViewportView(jList1);
button.setBounds(50, 600, 100, 20);
add(lab1);
add(lab2);
add(text1);
add(text2);
add(lab3);
add(small);
add(medium);
add(large);
add(toppers);
add(chk1);
add(chk2);
add(chk3);
add(chk4);
add(chk5);
add(lab4);
add(lab5);
add(button);
add(jScrollPane1);
text2.selectAll();
setVisible(true);
setSize(800, 700);
}
public void keyTyped(KeyEvent e) {
}
public void keyPressed(KeyEvent e) {
}
public void keyReleased(KeyEvent e) {
try {
Integer.parseInt(text2.getText());
} catch (NumberFormatException fe) {
text2.setText("");
}
refreshPrice();
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == button) {
JOptionPane.showMessageDialog(this, "Hi " + text1.getText() + ", thanks for ordering with us!"
+ "\n\nYour pizza's in the oven. ",
"Orders Confirmed", JOptionPane.INFORMATION_MESSAGE);
}
refreshPrice();
}
private void refreshPrice() {
double price = 0;
int numOfPizzas = Integer.parseInt(text2.getText());
NumberFormat numberForm = NumberFormat.getNumberInstance();
DecimalFormat moneyForm = (DecimalFormat) numberForm;
moneyForm.applyPattern("0.00");
if (small.isSelected()) {
price += smallPizzaPrice * numOfPizzas;
}
if (medium.isSelected()) {
price += mediumPizzaPrice * numOfPizzas;
}
if (large.isSelected()) {
price += largePizzaPrice * numOfPizzas;
}
if (chk1.isSelected()) {
price += mushroom * numOfPizzas;
}
if (chk2.isSelected()) {
price += sausage * numOfPizzas;
}
if (chk3.isSelected()) {
price += pineapple * numOfPizzas;
}
if (chk4.isSelected()) {
price += pepperoni * numOfPizzas;
}
if (chk5.isSelected()) {
price += ham * numOfPizzas;
}
lab5.setText("$" + moneyForm.format(price));
}
public static void main(String[] args) {
#SuppressWarnings("unused")
PizzaOrder order = new PizzaOrder();
}
#Override
public void valueChanged(ListSelectionEvent e) {
double price = 0;
int numOfPizzas = Integer.parseInt(text2.getText());
NumberFormat numberForm = NumberFormat.getNumberInstance();
DecimalFormat moneyForm = (DecimalFormat) numberForm;
moneyForm.applyPattern("0.00");
System.out.println(jList1.getSelectedIndex());
if(jList1.getSelectedIndex()==0) {
price += smallPizzaPrice * numOfPizzas;
}
if(jList1.getSelectedIndex()==1) {
price += mediumPizzaPrice * numOfPizzas;
}
if(jList1.getSelectedIndex()==2) {
price += largePizzaPrice * numOfPizzas;
}
lab5.setText("$" + moneyForm.format(price));
}
}

plMortgage Calculator GUI Issue with A Lot

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);
}
}

Categories