NullPointerException at actionPerformed. Not sure why - java

I am creating a Java program that uses a GUI to display a mortgage payment. I am trying to output to a textArea the payments that will be made for the mortgage. Here is my code:
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.text.DecimalFormat;
public class MortgageGui extends JFrame implements ActionListener {
// Set two-places for decimal format
DecimalFormat twoPlaces = new DecimalFormat("$0.00");
// Declare variable for calculation
Double loanAmt;
double interestRate;
double monthlyPayment;
int payment;
String amount;
JTextField loanAmount;
JComboBox loanTypeBox;
JLabel paymentOutput;
JTextArea paymentList;
// Build arrays for mortgages
double[] mortgage1 = {7.0, 5.35, 0.0}; // (years, interest, monthly payment)
double[] mortgage2 = {15.0, 5.5, 0.0}; // (years, interest, monthly payment)
double[] mortgage3 = {30.0, 5.75, 0.0}; // (years, interest, monthly payment)
public MortgageGui() {
super("Mortgage Calculator");
setLookAndFeel();
setSize(350, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Loan Amount Panel
JPanel loanAmtPanel = new JPanel();
JLabel loanAmtLabel = new JLabel("Loan Amount: ", JLabel.LEFT);
JTextField loanAmount = new JTextField(10);
loanAmtPanel.add(loanAmtLabel);
loanAmtPanel.add(loanAmount);
// Loan Type Panel
JPanel loanTypePanel = new JPanel();
JLabel loanTypeLabel = new JLabel("Loan Type: ", JLabel.LEFT);
String[] items = {"7 years at 5.35%", "15 years at 5.5%", "30 years at 5.75%"};
JComboBox loanTypeBox = new JComboBox(items);
loanTypePanel.add(loanTypeLabel);
loanTypePanel.add(loanTypeBox);
// Calculate Button Panel
JPanel calculatePanel = new JPanel();
JButton calcButton = new JButton("Calculate Paytment");
calcButton.addActionListener(this);
calculatePanel.add(calcButton);
// Monthly Payment Panel
JPanel paymentPanel = new JPanel();
JLabel paymentLabel = new JLabel("Monthly Payment: ", JLabel.LEFT);
JLabel paymentOutput = new JLabel("Calculated Payment");
paymentPanel.add(paymentLabel);
paymentPanel.add(paymentOutput);
// View Payments Panel
JPanel viewPayments = new JPanel();
JTextArea paymentList = new JTextArea("", 17, 27);
paymentList.setEditable(false);
paymentList.setLineWrap(true);
viewPayments.add(paymentList);
// Add panels to win Panel
JPanel win = new JPanel();
BoxLayout box = new BoxLayout(win, BoxLayout.Y_AXIS);
win.setLayout(box);
win.add(loanAmtPanel);
win.add(loanTypePanel);
win.add(calculatePanel);
win.add(paymentPanel);
win.add(viewPayments);
add(win);
// Make window visible
setVisible(true);
}
private void setLookAndFeel() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"
);
} catch (Exception exc) {
// ignore
}
}
public void actionPerformed(ActionEvent e) {
// Clear payment list
paymentList.setText("");
// Get loan amount from textfield
String amount = loanAmount.getText();
loanAmt = Double.valueOf(amount).doubleValue();
// Find which mortgate array to use from combobox
Object obj = loanTypeBox.getSelectedItem();
String loanSelected = obj.toString();
// Run the calculation based on the mortgage arrays
// 7-year loan
if (loanSelected.equals("7 years at 5.35%")) {
// Calculate payment, interest, and remaining
mortgage1[2] = (loanAmt + (loanAmt * (mortgage1[1] / 100))) / (mortgage1[0] * 12);
double interest1 = (loanAmt * (mortgage1[1] / 100)) / 84;
double amountRemaining1 = loanAmt + (loanAmt * (mortgage1[1] / 100));
// Loop through payments
for (int payment = 1; payment <=84; payment++) {
// Deduct one payment from the balance
amountRemaining1 = amountRemaining1 - mortgage1[2];
// Write payment to textArea
paymentList.append("Payment " + payment + ": $" + twoPlaces.format(mortgage1[2]) +
" / " + "Interest: $" + twoPlaces.format(interest1) + " / " +
"Remaining: $" + twoPlaces.format(amountRemaining1) + "\n");
}
} else {
// 15-year loan
if (loanSelected.equals("15 years at 5.5%")) {
// Calculate payment, interest, and remaining
mortgage2[2] = (loanAmt + (loanAmt * (mortgage2[1] / 100))) / (mortgage2[0] * 12);
double interest2 = (loanAmt * (mortgage2[1] / 100)) / 180;
double amountRemaining2 = loanAmt + (loanAmt * (mortgage2[1] / 100));
// Loop through payments
for (int payment = 1; payment <=180; payment++) {
// Deduct one payment from the balance
amountRemaining2 = amountRemaining2 - mortgage2[2];
// Write payment to textArea
paymentList.append("Payment " + payment + ": $" + twoPlaces.format(mortgage2[2]) +
" / " + "Interest: $" + twoPlaces.format(interest2) + " / " +
"Remaining: $" + twoPlaces.format(amountRemaining2) + "\n");
}
} else {
//30-year loan
//Calculate payment, interest, and remaining
mortgage3[2] = (loanAmt + (loanAmt * (mortgage3[1] / 100))) / (mortgage3[0] * 12);
double interest3 = (loanAmt * (mortgage3[1] / 100)) / 360;
double amountRemaining3 = loanAmt + (loanAmt * (mortgage3[1] / 100));
// Loop through payments
for (int payment = 1; payment <=360; payment++) {
// Deduct one payment from the balance
amountRemaining3 = amountRemaining3 - mortgage3[2];
// Write payment to textArea
paymentList.append("Payment " + payment + ": $" + twoPlaces.format(mortgage3[2]) +
" / " + "Interest: $" + twoPlaces.format(interest3) + " / " +
"Remaining: $" + twoPlaces.format(amountRemaining3) + "\n");
}
}
}
}
public static void main(String[] arguments) {
MortgageGui calc = new MortgageGui();
}
}
When I run the program I see the GUI but when I hit the button to calculate I get this in the console:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at MortgageGui.actionPerformed(MortgageGui.java:100)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2713)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:707)
at java.awt.EventQueue.access$000(EventQueue.java:101)
at java.awt.EventQueue$3.run(EventQueue.java:666)
at java.awt.EventQueue$3.run(EventQueue.java:664)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:680)
at java.awt.EventQueue$4.run(EventQueue.java:678)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:677)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:128)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:117)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:113)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
I cannot figure out where I am going wrong. Please help!

You're redeclaring the paymentList variable in the class's constructor
JTextArea paymentList = new JTextArea("", 17, 27);
The variable inside of the constructor "shadows" the class field, so that the constructor doesn't see the class field. This local variable is visible only within the constructor (since it was declared inside of it) and the class field will remain null.
Solution: don't re-declare the variable in the constructor. It's OK to initialize it there, but don't re-declare it:
paymentList = new JTextArea("", 17, 27);
On a more general note, you should always inspect the variables on the line that throws the NPE because one of them is null. If you saw that it was paymentList, you'd quickly be able to identify what I just showed you and you wouldn't need our help, which is kind of the goal of this forum -- to get you to be able to solve things on your own.
Edit:
Also please note that you do this error more than once in your code. I'll let you find the other occurrences of this.
Edit 2:
Consider putting your JTextArea in a JScrollPane. Consider using some decent layout managers and not setting the size of the GUI but rather letting the layout managers do this for you.

The field:
JTextArea paymentList;
is never initialized, so it is null when you try to set the value to "".
The same goes for loanAmount.
#Hovercraft Full Of Eels has explained why they aren't initialised as you think they are, in another answer...
Bonus tip: the line
loanAmt = Double.valueOf(amount).doubleValue();
will throw an exception if the loan amount is blank (or not a valid double) - you'll need to use a try-catch to handle this

"loanAmount", "loanTypeBox", "paymentList"
For these three, You have to comment out these three lines, because you have already declared these, only assignment needed;
//JTextField loanAmount = new JTextField(10); // loanAmount: Already declared, only assignment needed
loanAmount = new JTextField(10);
//JComboBox loanTypeBox = new JComboBox(items); // loanTypeBox: Already declared, only assignment needed
loanTypeBox = new JComboBox(items);
//JTextArea paymentList = new JTextArea("", 17, 27);// paymentList: Already declared, only assignment needed
paymentList = new JTextArea("", 17, 27);
Here is the updated code;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.text.DecimalFormat;
public class MortgageGui extends JFrame implements ActionListener {
// Set two-places for decimal format
DecimalFormat twoPlaces = new DecimalFormat("$0.00");
// Declare variable for calculation
Double loanAmt;
double interestRate;
double monthlyPayment;
int payment;
String amount;
JTextField loanAmount;
JComboBox loanTypeBox;
JLabel paymentOutput;
JTextArea paymentList;
// Build arrays for mortgages
double[] mortgage1 = { 7.0, 5.35, 0.0 }; // (years, interest, monthly
// payment)
double[] mortgage2 = { 15.0, 5.5, 0.0 }; // (years, interest, monthly
// payment)
double[] mortgage3 = { 30.0, 5.75, 0.0 }; // (years, interest, monthly
// payment)
public MortgageGui() {
super("Mortgage Calculator");
setLookAndFeel();
setSize(350, 500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Loan Amount Panel
JPanel loanAmtPanel = new JPanel();
JLabel loanAmtLabel = new JLabel("Loan Amount: ", JLabel.LEFT);
// JTextField loanAmount = new JTextField(10); // loanAmount: Already declared, only assignment needed
loanAmount = new JTextField(10);
loanAmtPanel.add(loanAmtLabel);
loanAmtPanel.add(loanAmount);
// Loan Type Panel
JPanel loanTypePanel = new JPanel();
JLabel loanTypeLabel = new JLabel("Loan Type: ", JLabel.LEFT);
String[] items = { "7 years at 5.35%", "15 years at 5.5%",
"30 years at 5.75%" };
// JComboBox loanTypeBox = new JComboBox(items); // loanTypeBox: Already declared, only assignment needed
loanTypeBox = new JComboBox(items);
loanTypePanel.add(loanTypeLabel);
loanTypePanel.add(loanTypeBox);
// Calculate Button Panel
JPanel calculatePanel = new JPanel();
JButton calcButton = new JButton("Calculate Paytment");
calcButton.addActionListener(this);
calculatePanel.add(calcButton);
// Monthly Payment Panel
JPanel paymentPanel = new JPanel();
JLabel paymentLabel = new JLabel("Monthly Payment: ", JLabel.LEFT);
JLabel paymentOutput = new JLabel("Calculated Payment");
paymentPanel.add(paymentLabel);
paymentPanel.add(paymentOutput);
// View Payments Panel
JPanel viewPayments = new JPanel();
// JTextArea paymentList = new JTextArea("", 17, 27); // paymentList: Already declared, only assignment needed
paymentList = new JTextArea("", 17, 27);
paymentList.setEditable(false);
paymentList.setLineWrap(true);
viewPayments.add(paymentList);
// Add panels to win Panel
JPanel win = new JPanel();
BoxLayout box = new BoxLayout(win, BoxLayout.Y_AXIS);
win.setLayout(box);
win.add(loanAmtPanel);
win.add(loanTypePanel);
win.add(calculatePanel);
win.add(paymentPanel);
win.add(viewPayments);
add(win);
// Make window visible
setVisible(true);
}
private void setLookAndFeel() {
try {
UIManager
.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception exc) {
// ignore
}
}
public void actionPerformed(ActionEvent e) {
// Clear payment list
paymentList.setText("");
// Get loan amount from textfield
String amount = loanAmount.getText();
loanAmt = Double.valueOf(amount).doubleValue();
// Find which mortgate array to use from combobox
Object obj = loanTypeBox.getSelectedItem();
String loanSelected = obj.toString();
// Run the calculation based on the mortgage arrays
// 7-year loan
if (loanSelected.equals("7 years at 5.35%")) {
// Calculate payment, interest, and remaining
mortgage1[2] = (loanAmt + (loanAmt * (mortgage1[1] / 100)))
/ (mortgage1[0] * 12);
double interest1 = (loanAmt * (mortgage1[1] / 100)) / 84;
double amountRemaining1 = loanAmt
+ (loanAmt * (mortgage1[1] / 100));
// Loop through payments
for (int payment = 1; payment <= 84; payment++) {
// Deduct one payment from the balance
amountRemaining1 = amountRemaining1 - mortgage1[2];
// Write payment to textArea
paymentList.append("Payment " + payment + ": $"
+ twoPlaces.format(mortgage1[2]) + " / "
+ "Interest: $" + twoPlaces.format(interest1) + " / "
+ "Remaining: $" + twoPlaces.format(amountRemaining1)
+ "\n");
}
} else {
// 15-year loan
if (loanSelected.equals("15 years at 5.5%")) {
// Calculate payment, interest, and remaining
mortgage2[2] = (loanAmt + (loanAmt * (mortgage2[1] / 100)))
/ (mortgage2[0] * 12);
double interest2 = (loanAmt * (mortgage2[1] / 100)) / 180;
double amountRemaining2 = loanAmt
+ (loanAmt * (mortgage2[1] / 100));
// Loop through payments
for (int payment = 1; payment <= 180; payment++) {
// Deduct one payment from the balance
amountRemaining2 = amountRemaining2 - mortgage2[2];
// Write payment to textArea
paymentList.append("Payment " + payment + ": $"
+ twoPlaces.format(mortgage2[2]) + " / "
+ "Interest: $" + twoPlaces.format(interest2)
+ " / " + "Remaining: $"
+ twoPlaces.format(amountRemaining2) + "\n");
}
} else {
// 30-year loan
// Calculate payment, interest, and remaining
mortgage3[2] = (loanAmt + (loanAmt * (mortgage3[1] / 100)))
/ (mortgage3[0] * 12);
double interest3 = (loanAmt * (mortgage3[1] / 100)) / 360;
double amountRemaining3 = loanAmt
+ (loanAmt * (mortgage3[1] / 100));
// Loop through payments
for (int payment = 1; payment <= 360; payment++) {
// Deduct one payment from the balance
amountRemaining3 = amountRemaining3 - mortgage3[2];
// Write payment to textArea
paymentList.append("Payment " + payment + ": $"
+ twoPlaces.format(mortgage3[2]) + " / "
+ "Interest: $" + twoPlaces.format(interest3)
+ " / " + "Remaining: $"
+ twoPlaces.format(amountRemaining3) + "\n");
}
}
}
}
public static void main(String[] arguments) {
MortgageGui calc = new MortgageGui();
}
}
And the output is as below with no any errors observed on the console;

Related

what is the difference between jpanel.updateUI() and jpanel.repaint() and toolkit.getDefultToolkit().sync() in java?

I'm making a simple app and learning with practicing how FPS-related methods work in java to make an app with a high fresh rate but, I don't know which one of the methods above should I use. my app have a button and a text field and a simple layout manager that I made which is supposed to change the location of the components according to the primal frame size (using ratio). the layout manager should be able to update the panel (or my frame I don't know really) every time that a component's location changed. also while the user is changing the frame size the components should move smoothly and without being laggy. how can I accomplish all these? right now my problem is shown below which seems that the panel.updateUI() doesn't do anything.
as you see there is a black line that will appear when you change the frame size slowly, and it doesn't disappear. when you do it fast it becomes bigger and you see it clearly but it disappears, while in FPS above 60 you shouldn't be able to see such a thing.
this is how I'm doing this currently:
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingWorker;
public class Test {
private JFrame frame;
private SwingWorker<Void, Void> sw;
private JTextField txtGi;
protected volatile static boolean b = false;
private double FPS = 0;
protected static volatile JButton btnStart;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Test window = new Test();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Test() {
initialize();
}
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 230, 230);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setMinimumSize(new Dimension(230, 230));
JPanel panel = new JPanel();
panel.setBounds(0, 0, 216, 193);
panel.setBackground(Color.PINK);
frame.getContentPane().add(panel);
panel.setLayout(null);
btnStart = new JButton("Start");
btnStart.setName("btnStart");
btnStart.setFont(new Font("Segoe Print", Font.BOLD | Font.ITALIC, 17));
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println(frame.getMinimumSize());
System.out.println(
"#sw.isDone(): " + sw.isDone() + " sw.isCancelled(): " + sw.isCancelled() + " b: " + b);
}
});
btnStart.setBounds(50, 120, 101, 33);
panel.add(btnStart);
System.out.println("1: " + Thread.currentThread().getName());
frame.validate();
panel.validate();
sw = new SwingWorker<Void, Void>() {
#Override
protected Void doInBackground() throws Exception {
b = true;
System.out.println(Thread.currentThread().getName() + " is going to sleep for 250 millis.");
System.out.println(frame.isShowing());
while (frame.isShowing() == false) {
System.out.println("initializing the frame.");
Thread.sleep(320);
}
System.out.println(frame.isShowing());
int cc = 0;
int FC = 0;
while (frame.isShowing()) {
Thread.sleep(1);
panel.updateUI();
long s = System.currentTimeMillis();
System.out.println("2: " + Thread.currentThread().getName());
cc++;
Graphical_AI.setComponentLocationWithButton(btnStart);
System.out.println("3: " + Thread.currentThread().getName());
if (Graphical_AI.thread1.isAlive()) {
System.out.println();
System.out.println("waiting for " + Graphical_AI.thread1.getName() + " to finish!");
System.out.println();
Graphical_AI.thread1.join();
Thread.sleep(1);
panel.updateUI();
}
Graphical_AI.setComponentLocationWithButton(txtGi);
if (Graphical_AI.thread1.isAlive()) {
System.out.println();
System.out.println("waiting for " + Graphical_AI.thread1.getName() + " to finish!");
System.out.println();
Graphical_AI.thread1.join();
Thread.sleep(1);
panel.updateUI();
}
long e = System.currentTimeMillis();
FPS = 1.0 / ((e - s) / 1000.0);
FC++;
if (FC == 60) {
txtGi.setText(String.valueOf("FPS: " + (int) FPS));
FC = 0;
}
System.out.println("FPS: " + (int) FPS);
if (cc == 1000) {
Thread.sleep(5);
cc = 0;
System.gc();
System.out.println("memory optimized.");
}
}
return null;
}
#Override
protected void process(List<Void> chunks) {
super.process(chunks);
}
#Override
protected void done() {
System.out.println("sw.isDone(): " + sw.isDone() + " b: " + b);
super.done();
}
};
sw.execute();
txtGi = new JTextField();
txtGi.setName("txtGi");
txtGi.setFont(new Font("Segoe Script", Font.BOLD | Font.ITALIC, 21));
txtGi.setBounds(50, 40, 134, 70);
panel.add(txtGi);
txtGi.setColumns(10);
}
}
the layout manager:
import java.awt.Container;
import java.util.ArrayList;
import javax.swing.JComponent;
import javax.swing.JFrame;
public class Graphical_AI {
protected static volatile int count = 0;
protected static volatile int C_X;
protected static volatile int C_Y;
protected static double x_C_To_E_ratio;
protected static double y_C_To_E_ratio;
protected static int C_WIDTH;
protected static int C_HEIGHT;
protected static int Con_WIDTH;
protected static int Con_HEIGHT;
protected static volatile int N_C_X;
protected static volatile int N_C_Y;
protected static Container con;
protected volatile static boolean bool = false;
protected static volatile ArrayList<Double> al = new ArrayList<Double>();
protected static volatile ArrayList<String> al_for_O_names = new ArrayList<String>();
protected static volatile String C_Name;
protected static volatile String C_O_Name;
protected volatile static boolean bool2 = false;
protected static volatile Thread thread1;
protected static void analyzeJComponentSize(JComponent comp) throws InterruptedException {
System.out.println("W: " + comp.getWidth() + " H: " + comp.getHeight());
Thread.sleep(30);
}
protected static void analyzeJFrameSize(JFrame frame) throws InterruptedException {
System.out.println("W: " + frame.getWidth() + " H: " + frame.getHeight());
Thread.sleep(30);
}
protected static void setComponentLocationWithButton(JComponent comp) throws InterruptedException {
thread1 = Thread.currentThread();
thread1 = new Thread(new Runnable() {
#Override
public void run() {
System.out.println("count: " + count);
C_Name = comp.getName();
System.out.println("C_Name: " + C_Name);
if (count == 0) {
C_O_Name = comp.getName();
System.out.println("C_O_Name: " + C_O_Name);
con = comp.getParent();
Con_WIDTH = con.getWidth();
Con_HEIGHT = con.getHeight();
System.out.println("** (double) Con_WIDTH: " + (double) Con_WIDTH);
System.out.println("** (double) Con_HEIGHT: " + (double) Con_HEIGHT);
x_C_To_E_ratio = (double) con.getWidth() / (double) comp.getX();
y_C_To_E_ratio = (double) con.getHeight() / (double) comp.getY();
if (bool2 == false) {
al.add(x_C_To_E_ratio);
al.add(y_C_To_E_ratio);
al_for_O_names.add(comp.getName());
bool2 = true;
}
System.out.println("** x_C_To_E_ratio: " + x_C_To_E_ratio);
System.out.println("** y_C_To_E_ratio: " + y_C_To_E_ratio);
System.out.println("** (double) con.getWidth() / (double) comp.getX(): "
+ (double) con.getWidth() / (double) comp.getX());
C_X = comp.getX();
C_Y = comp.getY();
C_WIDTH = comp.getWidth();
C_HEIGHT = comp.getHeight();
System.out.println("** C_WIDTH: " + C_WIDTH + ", " + C_HEIGHT);
System.out.println("** (double) con.getWidth() / (double) C_X): " + (double) con.getWidth() + " / "
+ (double) C_X);
count++;
}
if (C_Name != al_for_O_names.get(0)) {
count = 0;
System.out.println("%% C_Name: " + C_Name);
System.out.println("%% C_O_Name: " + C_O_Name);
System.out.println("%% al_for_O_names.get(0): " + al_for_O_names.get(0));
System.out.println("%% count became to:" + count);
al_for_O_names.remove(0);
al_for_O_names.add(comp.getName());
} else {
System.out.println("*ELSE STATEMENT*");
count = 1;
}
if (count == 0) {
C_Name = comp.getName();
System.out.println("$$ C_Name: " + C_Name);
con = comp.getParent();
Con_WIDTH = con.getWidth();
Con_HEIGHT = con.getHeight();
System.out.println("$$ (double) Con_WIDTH: " + (double) Con_WIDTH);
System.out.println("$$ (double) Con_HEIGHT: " + (double) Con_HEIGHT);
x_C_To_E_ratio = (double) con.getWidth() / (double) comp.getX();
y_C_To_E_ratio = (double) con.getHeight() / (double) comp.getY();
if (bool2 == false) {
al.add(x_C_To_E_ratio);
al.add(y_C_To_E_ratio);
bool2 = true;
}
System.out.println("$$ x_C_To_E_ratio: " + x_C_To_E_ratio);
System.out.println("$$ y_C_To_E_ratio: " + y_C_To_E_ratio);
System.out.println("$$ (double) con.getWidth() / (double) comp.getX(): "
+ (double) con.getWidth() / (double) comp.getX());
C_X = comp.getX();
C_Y = comp.getY();
C_WIDTH = comp.getWidth();
C_HEIGHT = comp.getHeight();
System.out.println("$$ C_WIDTH: " + C_WIDTH + ", " + C_HEIGHT);
System.out.println("$$ (double) con.getWidth() / (double) C_X): " + (double) con.getWidth() + " / "
+ (double) C_X);
count++;
}
try {
System.out.println("## after if count block ## comp W: " + comp.getWidth() + " comp H: "
+ comp.getHeight() + "\ncomp.getLocation(): " + comp.getLocation()
+ " comp.getLocationOnScreen(): " + comp.getLocationOnScreen());
System.out.println("con W: " + con.getWidth() + ", con H: " + con.getHeight());
if (x_C_To_E_ratio != al.get(0) || y_C_To_E_ratio != al.get(1)) {
x_C_To_E_ratio = al.get(0);
y_C_To_E_ratio = al.get(1);
Thread.sleep(2);
}
if (((double) con.getWidth() / (double) C_X) > x_C_To_E_ratio + 0.025) {
Thread.sleep(2);
System.out.println((((double) con.getWidth() / (double) C_X)) + " ,,, " + x_C_To_E_ratio);
while (((double) con.getWidth() / (double) C_X) > x_C_To_E_ratio + 0.025) {
C_X += 1;
N_C_X = C_X;
if (((double) con.getWidth() / (double) C_X) < x_C_To_E_ratio + 0.025) {
System.out.println("## in if bigger ## ");
break;
}
System.out.println("## in if bigger ## C_X: " + C_X + ", N_C_X " + N_C_X);
System.out.println("## in if bigger ## (double) con.getWidth() / (double) C_X: "
+ (double) con.getWidth() + " / " + (double) C_X);
System.out.println("## in if bigger ## ((double) con.getWidth() / (double) C_X): "
+ ((double) con.getWidth() / (double) C_X) + ", x_C_To_E_ratio:" + x_C_To_E_ratio
+ ", ((double) con.getWidth() / (double) C_X) == x_C_To_E_ratio: "
+ (((double) con.getWidth() / (double) C_X) == x_C_To_E_ratio));
if (((double) con.getWidth() / (double) C_X) == x_C_To_E_ratio
|| ((double) con.getWidth() / (double) C_X) - x_C_To_E_ratio < 0.002) {
bool = true;
System.out.println("## in if bigger ## GI.bool: " + bool);
System.out.println("## in if bigger ## W: " + comp.getWidth() + " H: "
+ comp.getHeight() + "\ncomp.getLocation(): " + comp.getLocation()
+ " comp.getLocationOnScreen(): " + comp.getLocationOnScreen() + " Con_WIDTH: "
+ Con_WIDTH + " Con_HEIGHT: " + Con_HEIGHT + " con.getWidth(): "
+ con.getWidth() + " con.getHeight(): " + con.getHeight());
System.out.println("## in if bigger ## $GI.bool: " + bool + " $Test.b: " + Test.b);
break;
}
comp.setBounds(N_C_X, comp.getY(), C_WIDTH, C_HEIGHT);
}
}
else if (((double) con.getWidth() / (double) C_X) < x_C_To_E_ratio - 0.025) {
Thread.sleep(2);
System.out.println((((double) con.getWidth() / (double) C_X)) + " *** " + x_C_To_E_ratio);
while (((double) con.getWidth() / (double) C_X) < x_C_To_E_ratio - 0.025) {
C_X -= 1;
N_C_X = C_X;
if (((double) con.getWidth() / (double) C_X) > x_C_To_E_ratio - 0.025) {
break;
}
System.out.println("C_X: " + C_X + ", N_C_X " + N_C_X);
System.out.println("(double) con.getWidth() / (double) C_X): " + (double) con.getWidth()
+ " / " + (double) C_X);
System.out.println("((double) con.getWidth() / (double) C_X): "
+ ((double) con.getWidth() / (double) C_X) + ", x_C_To_E_ratio:" + x_C_To_E_ratio
+ ", ((double) con.getWidth() / (double) C_X) == x_C_To_E_ratio: "
+ (((double) con.getWidth() / (double) C_X) == x_C_To_E_ratio));
if (((double) con.getWidth() / (double) C_X) == x_C_To_E_ratio
|| ((double) con.getWidth() / (double) C_X) - x_C_To_E_ratio > -0.002) {
bool = true;
System.out.println("GA.bool: " + bool);
System.out.println("W: " + comp.getWidth() + " H: " + comp.getHeight()
+ "\ncomp.getLocation(): " + comp.getLocation()
+ " comp.getLocationOnScreen(): " + comp.getLocationOnScreen() + " Con_WIDTH: "
+ Con_WIDTH + " Con_HEIGHT: " + Con_HEIGHT + " con.getWidth(): "
+ con.getWidth() + " con.getHeight(): " + con.getHeight());
System.out.println("$GA.bool: " + bool + " $T.b: " + Test.b);
break;
}
comp.setBounds(N_C_X, comp.getY(), C_WIDTH, C_HEIGHT);
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread1.start();
}
}
** Now the components don't seem to be laggy when you moving them while I appreciate it if you have any better solution.
** I don't want to use the pack() method or any prebuilt layout manager.
** I've already read a lot of similar questions but I didn't find my answer.
** I'm using eclipse windowbuilder.
I hadn't given this much thought since you said in your question,
I don't want to use the pack() method or any prebuilt layout manager.
This comment immediately disqualified your question in my mind. There was no way I could answer this question with this restriction.
Here's the simplest Swing FPS Test Example GUI I could come up with.
I use the pack method. I use Swing layout managers. If this is a problem, keep struggling on your own.
As I said in my comment, Oracle has a tutorial, Creating a GUI With JFC/Swing, that will take you through the steps of creating a Swing GUI. Skip the Netbeans section.
The first thing I did was call the SwingUtilities invokeLater method to start the Swing application. This method ensures that the Swing components are created and executed on the Event Dispatch Thread.
The next thing I did was construct a JFrame. The JFrame methods must be called in a specific order. This is the order I use for most of my Swing applications.
I constructed a button JPanel and a drawing JPanel. The button JPanel holds the Start JButton. The drawing JPanel draws the frames per second rate.
I used a Swing Timer to capture the current time and frame count. You can adjust the speed of the Timer by adjusting the int value in the Timer constructor. I don't recommend a value lower than 5.
Here's the complete runnable code.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.Rectangle2D;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
public class FPSTestExample implements Runnable {
public static void main(String[] args) {
SwingUtilities.invokeLater(new FPSTestExample());
}
private long startTime, endTime, countInterval;
private final DrawingPanel drawingPanel;
public FPSTestExample() {
this.drawingPanel = new DrawingPanel();
}
#Override
public void run() {
JFrame frame = new JFrame("FPS Test Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(drawingPanel, BorderLayout.CENTER);
frame.add(createButtonPanel(), BorderLayout.AFTER_LAST_LINE);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new FlowLayout());
panel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
JButton button = new JButton("Start");
panel.add(button);
button.addActionListener(new ActionListener() {
private Timer timer;
#Override
public void actionPerformed(ActionEvent event) {
if (timer == null) {
FPSTestExample.this.startTime = System.currentTimeMillis();
timer = new Timer(15, new FPSListener());
timer.start();
}
}
});
return panel;
}
public class DrawingPanel extends JPanel {
private static final long serialVersionUID = 1L;
public DrawingPanel() {
this.setPreferredSize(new Dimension(300, 200));
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (FPSTestExample.this.endTime > 0L) {
long elapsedTime = FPSTestExample.this.endTime -
FPSTestExample.this.startTime;
int fps = (int) (FPSTestExample.this.countInterval * 1000L /
elapsedTime);
String fpsString = "FPS: " + fps;
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.BLUE);
g2d.setFont(getFont().deriveFont(48f));
FontMetrics fm = g2d.getFontMetrics();
Rectangle2D r2d = fm.getStringBounds(fpsString, g2d);
int width = (int) Math.round(r2d.getWidth());
int height = (int) Math.round(r2d.getHeight());
int x = (getWidth() - width) / 2;
int y = (getHeight() - height + fm.getAscent()) / 2;
g2d.drawString(fpsString, x, y);
}
}
}
public class FPSListener implements ActionListener {
#Override
public void actionPerformed(ActionEvent event) {
FPSTestExample.this.endTime = System.currentTimeMillis();
FPSTestExample.this.countInterval++;
FPSTestExample.this.drawingPanel.repaint();
}
}
}

Why is my change calculator not working for coins?

I'm trying to make a program that calculates tax and what change needs to be given back, but for some reason, it doesn't tell me what coins to give back. The code tells me which bills I would need to give back, but the coins that are in the decimals don't work. I've tried looking all over stack exchange for a solution, but if I'm being honest, I'm not really sure what to even look for in the first place, so I haven't found a solution. I'm also new to Java and text-based coding in general, so any feedback is appreciated!
Here is my code:
import java.util.*;
public class Decisions1 {
static String taskValue = "C1";
public static void main(String[] args) {
//initiates the scanner
Scanner myInput = new Scanner(System.in);
//creates the variables for the total
double total1 = 0;
//asks for the total cost of all goods
System.out.println("Please enter the total cost of all goods. This program will add tax and calculate the change you must give back to the customer.");
total1 = myInput.nextDouble();
//performs calculations for tax
double tax2 = (total1*1.13);
double tax1 = (double) Math.round(tax2 * 100) / 100;
//creates variable for amount paid
double paid1 = 0;
//prints info to the user and asks how much cash they received
System.out.println("You entered $" + total1 + "\n" + "Total with tax = $" + tax1 + "\n" + "Please enter how much cash was paid by the customer. The amount of change owed to the customer will be displayed.");
paid1 = myInput.nextDouble();
//checks if customer has paid enough
if (tax1 > paid1) {
double owed1 = (tax1-paid1);
System.out.println("The customer still owes $" + owed1 + "!");
} else if (tax1 == paid1) { //checks if the customer has given exact change
System.out.println("The customer has paid the exact amount. You don't have to give them any change.");
} else if (tax1 < paid1) {
//starts change calculations
//variables for money units
double oneHundred = 100;
double fifty = 50;
double twenty = 20;
double ten = 10;
double five = 5;
double toonie = 2;
double loonie = 1;
double quarter = 0.25;
double dime = 0.10;
double nickel = 0.05;
double penny = 0.01;
//variable for change owed (rounded to 2 decimal places
double change1 = Math.round((paid1-tax1)*100)/100;
//calculates remainder
double oneHundredMod = (change1 % oneHundred);
//divides and removes decimal places
double oneHundredOwed = (change1 / oneHundred);
String oneHundredOwed1 = String.valueOf((int) oneHundredOwed);
//does the same thing for fifty
double fiftyMod = (oneHundredMod % fifty);
double fiftyOwed = (oneHundredMod / fifty);
String fiftyOwed1 = String.valueOf((int) fiftyOwed);
//twenties
double twentyMod = (fiftyMod % twenty);
double twentyOwed = (fiftyMod / twenty);
String twentyOwed1 = String.valueOf((int) twentyOwed);
//tens
double tenMod = (twentyMod % ten);
double tenOwed = (twentyMod / ten);
String tenOwed1 = String.valueOf((int) tenOwed);
//fives
double fiveMod = (tenMod % five);
double fiveOwed = (tenMod / five);
String fiveOwed1 = String.valueOf((int) fiveOwed);
//toonies
double tooniesMod = (fiveMod % toonie);
double tooniesOwed = (fiveMod / toonie);
String tooniesOwed1 = String.valueOf((int) tooniesOwed);
//loonies
double looniesMod = (tooniesMod % loonie);
double looniesOwed = (tooniesMod / loonie);
String looniesOwed1 = String.valueOf((int) looniesOwed);
//quarters
double quartersMod = (looniesMod % quarter);
double quartersOwed = (looniesMod / quarter);
String quartersOwed1 = String.valueOf((int) quartersOwed);
//dimes
double dimesMod = (quartersMod % dime);
double dimesOwed = (quartersMod / dime);
String dimesOwed1 = String.valueOf((int) dimesOwed);
//nickels
double nickelsMod = (dimesMod % nickel);
double nickelsOwed = (dimesMod / nickel);
String nickelsOwed1 = String.valueOf((int) nickelsOwed);
//and finally, pennies!
double penniesMod = (nickelsMod % penny);
double penniesOwed = (nickelsMod / penny);
String penniesOwed1 = String.valueOf((int) penniesOwed);
System.out.println("TOTAL CHANGE:" + "\n" + "\n" + "$100 Bill(s) = " + oneHundredOwed1 + "\n" + "$50 Bill(s) = " + fiftyOwed1 + "\n" + "$20 Bill(s) = " + twentyOwed1 + "\n" + "$10 Bill(s) = " + tenOwed1 + "\n" + "$5 Bill(s) = " + fiveOwed1 + "\n" + "Toonie(s) = " + tooniesOwed1 + "\n" +"Loonie(s) = " + looniesOwed1 + "\n" + "Quarter(s) = " + quartersOwed1 + "\n" + "Dime(s) = " + dimesOwed1 + "\n" + "Nickel(s) = " + nickelsOwed1 + "\n" + "Pennies = " + penniesOwed1);
}
}//end main
}// end Decisions1

How to get JTextArea text from another method

I want to use method from another class to append in my JTextArea (TEXT IS HERE in my code), how to do it?
SecondWindow() {
super("Mortage Loan Calculator");
setLayout(new FlowLayout(FlowLayout.LEFT, 20, 20));
tArea = new JTextArea(***TEXT IS HERE***, 30, 40);
scroll = new JScrollPane(tArea);
add(scroll);
setLocationRelativeTo(null);`
`And here is a method:
public void calcAnnuity(int years, int months, double amount, double rate){
double totalMonths = (12 * years) + months;
double partOfRate = rate / 12.0 / 100.0;
double tempAmount = amount;
double payment = amount * partOfRate * Math.pow(1 + partOfRate, totalMonths) / (Math.pow(1 + partOfRate, totalMonths) - 1); //mathematical formula
DecimalFormat decFormat = new DecimalFormat("#.##");
System.out.println(1 + " Payment = " + decFormat.format(payment) + "--- Left to pay: " + decFormat.format(amount));
for(int i = 2; i <= totalMonths; i++) {
tempAmount -= (payment - partOfRate * amount);
amount -= payment;
**textishere.append**(i + " Payment = " + decFormat.format(payment) + " --- Left to pay: " + decFormat.format(tempAmount));
}
}
Well, the easiest way would be to implement a public static method in your ClassA where the JTextArea is located.
public static setJTextAreaText(String text){
tArea.setText(text);
}
And in your ClassB you import ClassA and then call this method from your method calcAnnuity()
import ClassA;
public void calcAnnuity(int years, int months, double amount, double rate){
...
ClassA.setJTextAreaText('**textishere.append**');
}

Nullpointerexception and NumberFormatException java GUI [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am trying to make a GUI of a calculator which solves Parallel and Perpendicular Equations. It works when the GUI is not implemented but when I implement the GUI there are errors coming out such as nullpointerexception and numberformatexception. please do help me in resolving this.
import java.awt.*;
public class SuntayProjGUI {
JFrame frame;
private JTextField Ax;
private JTextField By;
private JTextField C;
private JTextField slopeLine;
private JTextField yintLine;
BigDecimal xCoefficient, yCoefficient, b, slope1, slope2, yIntercept1, yIntercept2, xCoord, yCoord; // declaration. Obvious naman na 'to
/**
* Launch the application.
* #param args
* #wbp.parser.entryPoint
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
SuntayProjGUI window = new SuntayProjGUI();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* #wbp.parser.entryPoint
*/
public SuntayProjGUI(){
initialize();
}
public void initialize(){
frame = new JFrame();
frame.getContentPane().setBackground(Color.PINK);
frame.getContentPane().setLayout(null);
Ax = new JTextField();
Ax.setBounds(46, 142, 116, 22);
frame.getContentPane().add(Ax);
Ax.setColumns(10);
By = new JTextField();
By.setBounds(46, 191, 116, 22);
frame.getContentPane().add(By);
By.setColumns(10);
C = new JTextField();
C.setBounds(46, 191, 116, 22);
frame.getContentPane().add(C);
C.setColumns(10);
JLabel lblPleaseChooseWhat = new JLabel("Please choose what inputs this calculator will receive");
lblPleaseChooseWhat.setBounds(12, 44, 302, 16);
frame.getContentPane().add(lblPleaseChooseWhat);
JComboBox comboBox = new JComboBox();
comboBox.setBounds(22, 76, 147, 22);
comboBox.addItem("Line with Y-intercept");
comboBox.addItem("Line with Point");
frame.getContentPane().add(comboBox);
//Computations
xCoefficient = new BigDecimal(Ax.getText());
yCoefficient = new BigDecimal(By.getText());
b = new BigDecimal(C.getText());
slope1 = getSlope(xCoefficient, yCoefficient);
yIntercept1 = getYIntercept(yCoefficient, b);
JLabel lblA = new JLabel("A :");
lblA.setBounds(12, 148, 36, 16);
frame.getContentPane().add(lblA);
JLabel lblB = new JLabel("B:");
lblB.setBounds(12, 194, 56, 16);
frame.getContentPane().add(lblB);
JLabel lblC = new JLabel("C:");
lblC.setBounds(12, 240, 56, 16);
frame.getContentPane().add(lblC);
C = new JTextField();
C.setBounds(46, 237, 116, 22);
frame.getContentPane().add(C);
C.setColumns(10);
JLabel lblLineAx = new JLabel("Line: Ax + By = C");
lblLineAx.setBounds(12, 111, 137, 16);
frame.getContentPane().add(lblLineAx);
JButton btnEnter = new JButton("Enter");
btnEnter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
frame.setVisible(false);
if(comboBox.equals("Line with Y-intercept")){
Line_with_yint lwy = new Line_with_yint();
lwy.frame.setVisible(true);
}
else if(comboBox.equals("Line with Point")){
Line_with_point lwp = new Line_with_point();
lwp.frame.setVisible(true);
}
}
});
btnEnter.setBounds(217, 383, 97, 25);
frame.getContentPane().add(btnEnter);
JLabel lblSlopeOfThe = new JLabel("Slope of the Line: ");
lblSlopeOfThe.setBounds(12, 291, 114, 16);
frame.getContentPane().add(lblSlopeOfThe);
slopeLine = new JTextField();
slopeLine.setEnabled(false);
slopeLine.setEditable(false);
slopeLine.setBounds(151, 288, 116, 22);
frame.getContentPane().add(slopeLine);
slopeLine.setColumns(10);
slopeLine.setText(slope1.toString());
JLabel lblYinterceptOfThe = new JLabel("Y-Intercept of the Line:");
lblYinterceptOfThe.setBounds(12, 332, 137, 16);
frame.getContentPane().add(lblYinterceptOfThe);
yintLine = new JTextField();
yintLine.setEnabled(false);
yintLine.setEditable(false);
yintLine.setBounds(151, 329, 116, 22);
frame.getContentPane().add(yintLine);
yintLine.setColumns(10);
yintLine.setText(yIntercept1.toString());
JButton btnCalculate = new JButton("Calculate");
btnCalculate.setBounds(217, 236, 97, 25);
frame.getContentPane().add(btnCalculate);
}
public static BigDecimal getSlope(BigDecimal x, BigDecimal y)
{
y = y.multiply(new BigDecimal(-1)); // yung pagmultiply sa -1 yung pagtranspose ng Ax + By = C -> By = -Ax + C
y = x.divide(y, 4, RoundingMode.CEILING); // eto yung pagdivide nung coefficient ni y sa both sides ng equation -> y = -Ax/B + C/B
return y;
}
public static BigDecimal getReciprocalSlope(BigDecimal x, BigDecimal y)
{
y = y.divide(x, 4, RoundingMode.CEILING).multiply(new BigDecimal(-1)); // eto yung reciprocal. obviously. balaiktarin lang. kung kanina
return y;
}
public static BigDecimal getYIntercept(BigDecimal y, BigDecimal b)
{
b = b.divide(y, 4, RoundingMode.CEILING); // yung pagkuha ng y-intercept similar dun sa getSlope pero ang difference since walang transposition, divide lang.
return b;
}
public static void getGEandSE(BigDecimal slope, BigDecimal xCoord, BigDecimal yCoord, BigDecimal yIntercept, BigDecimal x, BigDecimal y)
{
BigDecimal parallelA, parallelB, parallelC, perpendicularA, perpendicularB, perpendicularC;
if (x.compareTo(BigDecimal.ZERO) < 0) // itong part na 'to, kapag yung divisor (kasi diba either si y or x yung divisor, kapag slope na normal, si y, kapag nirereciprocate for perpendicular, si x diba.) negative, gagawing positive since lagi namang positive kapag nagdidivide both sides diba
x = x.multiply(new BigDecimal(-1));
if (y.compareTo(BigDecimal.ZERO) < 0)
y = y.multiply(new BigDecimal(-1));
if (yIntercept == null)
{
yCoord = yCoord.multiply(new BigDecimal(-1));
xCoord = xCoord.multiply(new BigDecimal(-1));
parallelA = slope.multiply(y).multiply(new BigDecimal(-1)); // eto yung diba kapag points ang given, y - y1 = m(x - x1). Yung coefficient ni x kasi si parallelA tapos transpose kaya may -1 tapos para mawala yung fraction, mumultiply by y. Gets naman kung bakit diba? Dito nagaganap yung -mx + y - y1 = mx1
parallelC = (xCoord.multiply(slope).multiply(new BigDecimal(-1))).add(yCoord).multiply(y); // kapag si C naman, diba y - y1 = m(x - x1) dito nagaganap yung didistribute si M tsaka ttranspose sa kabila. From y -y1 = m(x - x1) -> y - y1 + mx1 = mx
perpendicularA = getReciprocalSlope(x, y).multiply(x).multiply(new BigDecimal(-1)); // same principle lang, difference lang neto yung imbis na slope yung mumultiply, yung reciprocal nya (yung function dun na reciprocalSlope)
perpendicularC = (xCoord.multiply(getReciprocalSlope(x, y).multiply(new BigDecimal(-1))).add(yCoord)).multiply(x);
if (parallelC.compareTo(BigDecimal.ZERO) > 0)
System.out.println("Parallel Line GE: " + parallelA + "x + " + y + "y + " + parallelC + " = 0");
else
System.out.println("Parallel Line GE: " + parallelA + "x + " + y + "y - " + parallelC.multiply(new BigDecimal(-1)) + " = 0");
System.out.println("Parallel Line SE: " + parallelA + "x + " + y + "y = " + parallelC);
if (perpendicularC.compareTo(BigDecimal.ZERO) > 0)
System.out.println("Perpendicular Line GE: " + perpendicularA + "x + " + x + "y + " + perpendicularC + " = 0");
else
System.out.println("Perpendicular Line GE: " + perpendicularA + "x + " + x + "y - " + perpendicularC.multiply(new BigDecimal(-1)) + " = 0");
System.out.println("Perpendicular Line SE: " + perpendicularA + "x + " + x + "y = " + perpendicularC.multiply(new BigDecimal(-1)));
}
else
{
parallelA = slope.multiply(new BigDecimal(-1)).multiply(y); // gets mo na siguro 'to. Kung ano nasa notes mo at yung pagkakahawig nya sa nasa taas ganun din
parallelC = yIntercept.multiply(new BigDecimal(-1)).multiply(y);
perpendicularA = getReciprocalSlope(x, y).multiply(new BigDecimal(-1)).multiply(x);
perpendicularC = yIntercept.multiply(new BigDecimal(-1)).multiply(x);
if (parallelC.compareTo(BigDecimal.ZERO) > 0)
System.out.println("Parallel Line GE: " + parallelA + "x + " + y + "y + " + parallelC + " = 0");
else
System.out.println("Parallel Line GE: " + parallelA + "x + " + y + "y - " + parallelC.multiply(new BigDecimal(-1)) + " = 0");
System.out.println("Parallel Line SE: " + parallelA + "x + " + y + "y = " + parallelC.multiply(new BigDecimal(-1)));
if (perpendicularC.compareTo(BigDecimal.ZERO) > 0)
System.out.println("Perpendicular Line GE: " + perpendicularA + "x + " + x + "y + " + perpendicularC + " = 0");
else
System.out.println("Perpendicular Line GE: " + perpendicularA + "x + " + x + "y - " + perpendicularC.multiply(new BigDecimal(-1)) + " = 0");
System.out.println("Perpendicular Line SE: " + perpendicularA + "x + " + x + "y = " + perpendicularC);
}
}
}
and when I try to run this, there are errors:
java.lang.NumberFormatException
at java.math.BigDecimal.<init>(BigDecimal.java:596)
at java.math.BigDecimal.<init>(BigDecimal.java:383)
at java.math.BigDecimal.<init>(BigDecimal.java:806)
at SuntayProjGUI.initialize(SuntayProjGUI.java:83)
at SuntayProjGUI.<init>(SuntayProjGUI.java:47)
at SuntayProjGUI$1.run(SuntayProjGUI.java:34)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
thank you for answering
You'r trying to get a text from a text box which should be empty after initializing.
Therefore you'r calling new BigDecimal("") which will throw an NumberFormatException.
The NullpointerException will probably get thrown because new BigDecimal failed to create an Object.
You need to do the computations after the fields got filled.
EDIT:
Also it looks like C hasn't been initialized at this point of code.
xCoefficient = new BigDecimal(Ax.getText());
yCoefficient = new BigDecimal(By.getText());
b = new BigDecimal(C.getText());
EDIT2: You could move everything which should only be done after entering values into a method and call this method via a button.
#Nordiii already explained the reason behind your problem. So, i am not repeating it.
The computation part of your code should be in actionPerformed method of your Calculate Button.
EDIT:
btnCalculate.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
xCoefficient = new BigDecimal(Ax.getText());
yCoefficient = new BigDecimal(By.getText());
b = new BigDecimal(C.getText());
slope1 = getSlope(xCoefficient, yCoefficient);
yIntercept1 = getYIntercept(yCoefficient, b);
slopeLine.setText(slope1.toString());
yintLine.setText(yIntercept1.toString());
}
});
Also set default frame size
frame.setBounds(100, 100, 468, 369);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Java Button for program

Im in need of help with my java program code. Basically it is a program that allows users to request an item and the amount they want. If it is in stock they can click a "buy" button. Once clicked a confirm dialog will pop up asking if the user will like to buy 'x' units for 'y' amount. They can either choose yes, no or cancel. If they choose yes a pop up frame with the reciept will come up (havent done this part yet). The problem that i am having is that if they click no or cancel the reciept frame still shows - I dont want it to do this. Please can you tell me what is wrong with my code as it is not performing how i want it to perform. p.s. im a beginner in java as ive only been learning for a month
enter code here
public PurchaseItem() {
this.setLayout(new BorderLayout());
JPanel top = new JPanel();
top.setLayout(new FlowLayout(FlowLayout.CENTER));
JPanel bottom = new JPanel();
bottom.setLayout(new FlowLayout(FlowLayout.CENTER));
bottom.add(Buy);
this.add(bottom, BorderLayout.SOUTH);
setBounds(100, 100, 450, 250);
setTitle("Purchase Item");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
top.add(new JLabel("Enter Item Key:"));
top.add(ItemNo);
top.add(new JLabel ("Enter Amount:"));
top.add(AmountNo);
top.add(check);
Buy.setText("Buy"); Buy.setVisible(true);
check.addActionListener(this);
Buy.addActionListener(this);
add("North", top);
JPanel middle = new JPanel();
middle.add(information);
add("Center", middle);
setResizable(true);
setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e) {
String ItemKey = ItemNo.getText();
String ItemAmount = AmountNo.getText();
String Name = StockData.getName(ItemKey);
int Yes = JOptionPane.YES_OPTION;
int No = JOptionPane.NO_OPTION;
int Amount = Integer.parseInt(ItemAmount);
int Key = Integer.parseInt(ItemKey);
int NewStock = StockData.getQuantity(ItemKey) - Amount;
double Total = Integer.parseInt(ItemAmount) * StockData.getPrice(ItemKey);
if (Name == null){
information.setText("There is no such item");
}
else if (Amount > StockData.getQuantity(ItemKey)) {
information.setText("Sorry there is not enough stock available");
}
else {
information.setText(Name + " selected: " + ItemAmount);
information.append("\nIndividual Unit Price: " + pounds.format(StockData.getPrice(ItemKey)));
information.append("\nCurrent Stock Available: " + StockData.getQuantity(ItemKey));
information.append("\nNew Stock After Sale: " + NewStock);
information.append("\n\nTotal: " + ItemAmount + " Units" + " at " + pounds.format(StockData.getPrice(ItemKey)) + " each");
information.append("\n= " + pounds.format(Total));
}
if (e.getSource() == Buy) {
JOptionPane.showConfirmDialog(null, "Buy " + ItemAmount + " Units" + " for " + pounds.format(Total) + "?");
if (Yes == JOptionPane.YES_OPTION) {
JFrame frame2 = new JFrame();
frame2.pack(); frame2.setBounds(250, 250, 500, 500); frame2.setTitle("Reciept"); frame2.setVisible(true);
JPanel middle = new JPanel();
middle.setLayout(new FlowLayout(FlowLayout.CENTER));
middle.add(reciept);
reciept.setBounds(260,260,400,400);
reciept.setVisible(true);
}
}
}
}
if (Yes == JOptionPane.YES_OPTION) { is always true (Yes been equal to JOptionPane.YES_OPTION; int Yes = JOptionPane.YES_OPTION;).
You need to get the return value from JOptionPane.showConfirmDialog and compare that
int response = JOptionPane.showConfirmDialog(null, "Buy " + ItemAmount + " Units" + " for " + pounds.format(Total) + "?");
if (response == JOptionPane.YES_OPTION) {
...
}

Categories

Resources