Nullpointerexception and NumberFormatException java GUI [duplicate] - java

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

Related

How to call variables from another class into an ActionListener method?

I would like to apologize in advance I am new to java and don't know very much so stick with me please. I would like to know how to get my character attributes from one ActionListener method in one class to another ActionListener method in another class. I would like to get the inputs from the user about player1 in one class and then use them in the other class. Please help, and I appreciate your time.
public void actionPerformed(ActionEvent event) {
// TODO Auto-generated method stub
if(event.getSource() == create){
Character player1 = new Character( Integer.parseInt(strength.getText()), Integer.parseInt(defense.getText()), Integer.parseInt(health.getText()) , Integer.parseInt(dexterity.getText()));
player1.name = name.getText();
JOptionPane.showMessageDialog(this, "\nName: " + player1.name + "\nHealth: " + player1.health + "\nStrength: " + player1.strength + "\nDefense: " + player1.defense + "\nDexterity: " + player1.dexterity);
dispose();//To close the current window
GameWindow gwindow = new GameWindow();
gwindow.setVisible(true);//Open the new window
}
put into
#Override
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
Character Goblin = new Character(10, 3, 6, 10);
Character Witch = new Character(2, 7, 3, 20);
Character Zombie = new Character(5, 5, 5, 15);
int damage;
if (event.getSource() == right) {
label1.setText("You have encountered a goblin!");
label2.setText("Do you wish to fight or flee?");
fight.setVisible(true);
flee.setVisible(true);
}
if(event.getSource() == fight) {
System.out.println(player1 + " VS. " + Goblin.name);
while(player1.isAlive() && Goblin.isAlive()){
// player 1 attack
damage = player1.attack(Goblin);
System.out.println(player1.name + " hits " + Goblin.name + " for " + damage + " damage.");
// player 2 attack
damage = Goblin.attack(player1);
System.out.println(Goblin.name + " hits " + player1.name + " for " + damage + " damage.\n");
}
// Check to see who won
if( player1.isAlive()){
System.out.println(player1.name + " wins!");
}
else{
System.out.println("You have perished");
}
}
}
Declare Player1 as public Static member
So it's Value can;t be changed.
and You can use player1 Through the object of that particular Class.
Class First{
//Declare That Character object as a static public here
//Player1;
}
Class Second{
//First Create Object Of that class....
First f = new First(//Parameter For Constructor);
f.Player1;
}
Change your GameWindow constructor like this.
class GameWindow extends JFrame implements ActionListener{
private Character player1;
public GameWindow(Character player1){
this.player1 = player1;
}
#Override
public void actionPerformed(ActionEvent event) {
Object source = event.getSource();
Character Goblin = new Character(10, 3, 6, 10);
Character Witch = new Character(2, 7, 3, 20);
Character Zombie = new Character(5, 5, 5, 15);
int damage;
if (event.getSource() == right) {
label1.setText("You have encountered a goblin!");
label2.setText("Do you wish to fight or flee?");
fight.setVisible(true);
flee.setVisible(true);
}
if(event.getSource() == fight) {
System.out.println(player1 + " VS. " + Goblin.name);
while(player1.isAlive() && Goblin.isAlive()){
// player 1 attack
damage = player1.attack(Goblin);
System.out.println(player1.name + " hits " + Goblin.name + " for " + damage + " damage.");
// player 2 attack
damage = Goblin.attack(player1);
System.out.println(Goblin.name + " hits " + player1.name + " for " + damage + " damage.\n");
}
// Check to see who won
if( player1.isAlive()){
System.out.println(player1.name + " wins!");
}
else{
System.out.println("You have perished");
}
}
}
}
And pass parameter to new contructor.
public void actionPerformed(ActionEvent event) {
// TODO Auto-generated method stub
if(event.getSource() == create){
Character player1 = new Character( Integer.parseInt(strength.getText()), Integer.parseInt(defense.getText()), Integer.parseInt(health.getText()) , Integer.parseInt(dexterity.getText()));
player1.name = name.getText();
JOptionPane.showMessageDialog(this, "\nName: " + player1.name + "\nHealth: " + player1.health + "\nStrength: " + player1.strength + "\nDefense: " + player1.defense + "\nDexterity: " + player1.dexterity);
dispose();//To close the current window
GameWindow gwindow = new GameWindow(player1);
gwindow.setVisible(true);//Open the new window
}

Finding GCD java

Good Day! I have a problem on my code. It has an error and here's is the picture:
Here is my code:
private static int gcd(int a, int b, int c) {
return gcd(gcd(a,b),c);
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//DecimalFormat fmt = new DecimalFormat("+##");
int x1 , y1, x2, y2, gcd,
inverted_x1, inverted_y1, inverted_x2, inverted_y2,
x1Times2, x2Times2, y1Times2, y2Times2,
x1raised, y1raised, x2raised, y2raised,
computeX, computeY, computeS,
x2inverted, y2inverted, invertedx2times2, invertedy2times2;
try{
x1 = Integer.parseInt(jTextField1.getText());
y1 = Integer.parseInt(jTextField2.getText());
x2 = Integer.parseInt(jTextField3.getText());
y2 = Integer.parseInt(jTextField4.getText());
int[] array = new int[4];
array[0] = x1;
array[1] = x2;
array[2] = y1;
array[3] = y2;
inverted_x1 = x1 *= -1;
inverted_y1 = y1 *= -1;
inverted_x2 = x2 *= -1;
inverted_y2 = y2 *= -1;
jTextField5.setText("= (x" + formatSign(inverted_x1) + ")² + (y" + formatSign(inverted_y1) + ")²"
+ " = (x" + formatSign(inverted_x2) + ")² + (y" + formatSign(inverted_y2) + ")²" );
x1Times2 = inverted_x1*2;
y1Times2 = inverted_y1*2;
x2Times2 = inverted_x2*2;
y2Times2 = inverted_y2*2;
x1raised = inverted_x1*inverted_x1;
y1raised = inverted_y1*inverted_y1;
x2raised = inverted_x2*inverted_x2;
y2raised = inverted_y2*inverted_y2;
jTextField9.setText("= x²" + formatSign(x1Times2) + "x" + formatSign(x1raised) + "+y²" + formatSign(y1Times2)
+ "y" + formatSign(y1raised) + "= x²" + formatSign(x2Times2) + "x" + formatSign(x2raised) + "+y²"
+ formatSign(y2Times2) + "y" + formatSign(y2raised));
x2inverted = x2raised *= -1;
y2inverted = y2raised *= -1;
invertedx2times2 = x2Times2 *= -1;
invertedy2times2 = y2Times2 *= -1;
computeX = x1Times2 + invertedx2times2;
computeY = y1Times2 + invertedy2times2;
computeS = x2inverted + y2inverted + x1raised + y1raised;
jTextField17.setText("= " + formatSign(computeX) + "x" + formatSign(computeY) + "y" + formatSign(computeS) + "= 0");
gcd = gcd(computeX, computeY, computeS);
jTextField18.setText("= " + formatSign(computeX/gcd) + "x" + formatSign(computeY/gcd) + "y" + formatSign(computeS/gcd) + "= 0");
jTextField6.setText("= " + formatSign(10/gcd));
XYLineChart_AWT chart = new XYLineChart_AWT("Locus of Point Graph", "", array);
chart.pack();
RefineryUtilities.centerFrameOnScreen( chart );
chart.setVisible( true );
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Please fill necessary inputs");
}
}
the error shows at my return gcd(gcd(a,b),c);
I want to get the GCD of 3 numbers and later on divide it to my variables. Is there any other way? Or is there a way to solve the error?
Thanks in advance!
Because gcd(...) takes 3 arguments
private static int gcd(int a, int b, int c) {
return gcd(gcd(a,b),c);
}
In return, you are passing only 2. Also, with the code you have shown, if you pass 3 params, it will be infinite recursion. Thanks to #eis for pointing that out. I forgot to mention it :)

User Interface in java

I am trying to design a UI for tic tac toe in java but I don't understand why is their a 5th row in the UI.I want to have four rows where bottom three rows would serve as buttons for Board of tictactoe and top row would be used as display toshow important messages to the users . I have attached the code and a snapshot of the UI.
//code
package TicTacToe;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class TicTacToeUI extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
JPanel[] row = new JPanel[4];
JButton[] button = new JButton[9];
String[] buttonString = {" "," "," ",
" "," "," ",
" "," "," "};
Dimension displayDimension = new Dimension(290, 45);
Dimension regularDimension = new Dimension(90, 90);
JTextArea display = new JTextArea(2, 20);
Font font = new Font("Times new Roman", Font.BOLD, 14);
public TicTacToeUI(){
super("TicTacToe");
setDesign();
setSize(350, 500);
setResizable(false);
setDefaultCloseOperation(EXIT_ON_CLOSE);
GridLayout grid = new GridLayout(5,5);
setLayout(grid);
FlowLayout f1 = new FlowLayout(FlowLayout.CENTER);
FlowLayout f2 = new FlowLayout(FlowLayout.CENTER,1,1);//gap in cells
for(int i = 0; i < 4; i++ )
row[i] = new JPanel();
row[0].setLayout(f1);
for(int i = 1; i < 4; i++)
row[i].setLayout(f2);
for(int i = 0; i < 9; i++) {
button[i] = new JButton();
button[i].setText(buttonString[i]);
button[i].setBackground(Color.black);
button[i].setFont(font);
button[i].addActionListener(this);
}
display.setFont(font);
display.setEditable(false);
display.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
display.setPreferredSize(displayDimension);
for(int i = 0; i < 9; i++)
button[i].setPreferredSize(regularDimension);
row[0].add(display);
add(row[0]);
for(int i=1,k=0;i<4&&k<9;i++){
for(int j=0;j<3;j++){
row[i].add(button[k]);
k++;
}
add(row[i]);
}
setVisible(true);
}
public final void setDesign() {
try {
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
} catch(Exception e) {
}
}
public static void main(String[] args) {
TicTacToeUI obj = new TicTacToeUI();
}
#Override
public void actionPerformed(ActionEvent ae) {
// TODO Auto-generated method stub
int x,y;
if(ae.getSource()==button[0]){
x=0;
y=0;
display.setText("x = " + x + "y = " + y);
}
else if(ae.getSource()==button[1]){
x=0;
y=1;
display.setText("x = " + x + "y = " + y);
}
else if(ae.getSource()==button[2]){
x=0;
y=2;
display.setText("x = " + x + "y = " + y);
}
else if(ae.getSource()==button[3]){
x=1;
y=0;
display.setText("x = " + x + "y = " + y);
}
else if(ae.getSource()==button[4]){
x=1;
y=1;
display.setText("x = " + x + "y = " + y);
}
else if(ae.getSource()==button[5]){
x=1;
y=2;
display.setText("x = " + x + "y = " + y);
}
else if(ae.getSource()==button[6]){
x=2;
y=0;
display.setText("x = " + x + "y = " + y);
}
else if(ae.getSource()==button[7]){
x=2;
y=1;
display.setText("x = " + x + "y = " + y);
}
else if(ae.getSource()==button[8]){
x=2;
y=2;
display.setText("x = " + x + "y = " + y);
}
}
}
Well, I'm not sure if I understand your question, because the problem you have is in this line:
GridLayout grid = new GridLayout(5,5);
I you want to have 4 rows then just change it to:
GridLayout grid = new GridLayout(4,5);
Hope it helps.

Method calculations wrong when used in JTable, but correct when printed out in console

I have a triangle program that I wrote as an assignment for my intro to JAVA class. Everything seems to work great, except that a) some of my numbers are showing up as squares in the table, and b) my getPerimeter() method that is being called in the table is not producing the same results as the same method called in a System.out.println; statement. Maybe the two problems stem from the same issue, I'm not sure.
Here is what I believe is the relevant code from my Triangle.java:
public String getAngleA()
{
double a = sideA;
double b = sideB;
double c = sideC;
angleA = Math.toDegrees(Math.acos((c*c + b*b - a*a) / (2 * b * c)));
return df.format(angleA);
}
public String getAngleB()
{
double a = sideA;
double b = sideB;
double c = sideC;
angleB = Math.toDegrees(Math.acos((a*a + c*c - b*b) / (2 * a* c)));
return df.format(angleB);
}
public String getAngleC()
{
angleC = 180 - (angleA + angleB);
return df.format(angleC);
}
public String getPerimeter()
{
perimeter = sideA + sideB + sideC;
return df.format(perimeter);
}
And, here is all the code from my TriangleTester.java, as I have no clue where the problem lies:
Scanner in = new Scanner(System.in);
System.out.println("Enter X coordinate for the first corner of the triangle: ");
int x1 = in.nextInt();
System.out.println("Enter Y coordinate for the first corner of the triangle: ");
int y1 = in.nextInt();
System.out.println("Enter X coordinate for the second corner of the triangle: ");
int x2 = in.nextInt();
System.out.println("Enter Y coordinate for the second corner of the triangle: ");
int y2 = in.nextInt();
System.out.println("Enter X coordinate for the third corner of the triangle: ");
int x3 = in.nextInt();
System.out.println("Enter Y coordinate for the third corner of the triangle: ");
int y3 = in.nextInt();
Triangle myTri = new Triangle(x1, y1, x2, y2, x3, y3);
JFrame frame = new JFrame();
String[] columnName = {"SIDES", "ANGLES", "PERIMETER", "AREA"};
Object[][] data = {
{"The length your triangle on side A is: " + myTri.getSideA(),
"Angle A = " + myTri.getAngleA() + "\u00b0",
"The perimeter of your triangle is: " + myTri.getPerimeter(),
"The area of your triangle is: " + myTri.getArea()},
{"The length your triangle on side B is: " + myTri.getSideB(),
"Angle B = " + myTri.getAngleB() + "\u00b0",
" ", " "},
{"The length your triangle on side C is: " + myTri.getSideC(),
" Angle C = " + myTri.getAngleC() + "\u00b0",
" ", " "},
};
JTable table = new JTable(data, columnName);
DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment( JLabel.LEFT );
table.getColumnModel().getColumn(1).setCellRenderer(centerRenderer);
centerRenderer.setHorizontalAlignment( JLabel.CENTER );
table.getColumnModel().getColumn(2).setCellRenderer(centerRenderer);
table.getColumnModel().getColumn(3).setCellRenderer(centerRenderer);
frame.setSize(950,107);
frame.setVisible(true);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Your Triangle");
frame.add(table.getTableHeader(),BorderLayout.PAGE_START);
frame.add(table);
System.out.println(myTri.getP1() + "\n" + myTri.getP2() + "\n" + myTri.getP3() + "\n");
System.out.println("The length of triangle on side A is: " + myTri.getSideA());
System.out.println("The length of triangle on side B is: " + myTri.getSideB());
System.out.println("The length of triangle on side C is: " + myTri.getSideC() + "\n");
System.out.println("Angle A is: " + myTri.getAngleA() + "\u00b0");
System.out.println("Angle B is: " + myTri.getAngleB() + "\u00b0");
System.out.println("Angle C is: " + myTri.getAngleC() + "\u00b0" + "\n");
System.out.println("Perimeter is: " + myTri.getPerimeter() +"\n");
System.out.println("Area is: " + myTri.getArea());
}
}
And lastly, here is a pic showing the table with the squares and the wrong perimeter output, and below that, you can see the console print out with the right numbers, so I know that my methods are correct.
My problem was that the getAngle() methods were being called in my table before the getSides() methods were being run, so there were no values for the getAngle() methods to use. The all worked in my command line print out because all the methods were being run in "order," so the getSides() methods had all run before I called the first getAngle() method. Here's the fixed relevant code:
double sideA = myTri.getSideA();
double sideB = myTri.getSideB();
double sideC = myTri.getSideC();
double angleA = myTri.getAngleA();
double angleB = myTri.getAngleB();
double angleC = myTri.getAngleC();
double perim = myTri.getPerimeter();
double area = myTri.getArea();
String[] columnName = {"SIDES", "ANGLES", "PERIMETER", "AREA"};
Object[][] data = {
{"Side A = " + df.format(sideA),
"Angle A = " + df.format(angleA) + "\u00b0",
"Perimeter = " + df.format(perim),
"Area = " + df.format(area)},
{"Side B = " + df.format(sideB),
"Angle B = " + df.format(angleB) + "\u00b0",
" ", " "},
{"Side C = " + df.format(sideC),
"Angle C = " + df.format(angleC) + "\u00b0",
" ", " "}
};
And, the reason I mixed command line output with a GUI output was because my GUI output wasn't working, and I needed a way to tell if my numbers were being calculated correctly. Clearly, I would not turn in or release a program that ran that way.

JPanel GUI is updating itself

I am making a simple clicker type game. The problem is, my JPanel is ignoring the Swing Timer I have set to it to update every second and is instead updating every millisecond on it's own, even if I remove the timer. Repaint is not called anywhere except the timer's listener, so the JPanel is repainting itself without my instruction, does anyone know why this would be happening?
public GameGUI() {
sectors.add(new Sector());
add(recourseMonitor);
recourseMonitor.setOpaque(false);
recourseMonitor.setFocusable(false);
add(buyHShip);
buyHShip.setToolTipText("Extracts Hydrogren directly from the core of a star.");
buyHShip.addActionListener(this);
add(buyCShip);
buyCShip.setToolTipText("Extracts Carbon from indigenous lifeforms.");
buyCShip.addActionListener(this);
add(buyIShip);
add(buyUShip);
buyUShip.setToolTipText("Extracts Uranium from nuclear waste leftovers.");
buyUShip.addActionListener(this);
buyIShip.setToolTipText("Strip mines nearby planets for Iron.");
buyIShip.addActionListener(this);
add(buyAShip);
buyAShip.setToolTipText("Collects Antimatter from the fabric of the universe.");
buyAShip.addActionListener(this);
add(buyCookieShip);
buyCookieShip.setToolTipText("Rips holes in the space-time continuum to "
+ "bring back cookies from an ancient civilization.");
buyCookieShip.addActionListener(this);
add(buyTShip);
buyTShip.addActionListener(this);
add(cashButton);
cashButton.addActionListener(this);
add(sellHplus);
sellHplus.addActionListener(this);
add(sellCplus);
sellCplus.addActionListener(this);
add(sellIplus);
sellIplus.addActionListener(this);
add(sellUplus);
sellUplus.addActionListener(this);
add(sellAplus);
sellAplus.addActionListener(this);
add(sellCookieplus);
sellCookieplus.addActionListener(this);
add(sellHminus);
sellHminus.addActionListener(this);
add(sellCminus);
sellCminus.addActionListener(this);
add(sellIminus);
sellIminus.addActionListener(this);
add(sellUminus);
sellUminus.addActionListener(this);
add(sellAminus);
sellAminus.addActionListener(this);
add(sellCookieminus);
sellCookieminus.addActionListener(this);
add(hBeingSold);
add(cBeingSold);
add(iBeingSold);
add(uBeingSold);
add(aBeingSold);
add(cookiesBeingSold);
if (debug == true) {
add(testButton);
testButton.addActionListener(this);
}
}
#Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
buyHShip.setText("[" + sectors.get(0).getStation().gethShip() + "] "
+ "Buy Hydrogen Extractor: " + hPrice);
buyCShip.setText("[" + sectors.get(0).getStation().getcShip() + "] "
+ "Buy Carbon Miner: " + cPrice);
buyUShip.setText("[" + sectors.get(0).getStation().getuShip() + "] "
+ "Buy Uranium Miner: " + uPrice);
buyIShip.setText("[" + sectors.get(0).getStation().getiShip() + "] "
+ "Buy Iron Miner: " + iPrice);
buyAShip.setText("[" + sectors.get(0).getStation().getaShip() + "] "
+ "Buy Antimatter Collector: " + aPrice);
buyCookieShip.setText("[" + sectors.get(0).getStation().getcChip() + "] "
+ "Buy Cookie Drone: " + cookiePrice);
buyTShip.setText("[" + sectors.get(0).getStation().gettShip() + "] "
+ "Buy Trading Ship: " + tradePrice);
hBeingSold.setText("Hydrogen being sold: " + tradeH);
cBeingSold.setText("Carbon being sold: " + tradeC);
iBeingSold.setText("Iron being sold: " + tradeI);
uBeingSold.setText("Uranium being sold: " + tradeU);
aBeingSold.setText("Antimatter being sold: " + tradeA);
cookiesBeingSold.setText("Cookies being sold: " + tradeCookie);
recourseMonitor.setText("Space Cash: " + spaceCash
+ "\nEnergy: " + energy
+ "\nHydrogen: " + hydrogen
+ "\nCarbon: " + carbon
+ "\nUranium: " + uranium
+ "\nIron: " + iron
+ "\nAntimatter: " + antimatter
+ "\nCookies: " + cookies);
drawItems(g);
playGame();
}
public void drawItems(Graphics g) {
super.paintComponent(g);
recourseMonitor.setLocation(5, 0);
buyHShip.setLocation(getWidth() - buyHShip.getWidth(), 0);
buyCShip.setLocation(getWidth() - buyCShip.getWidth(), buyCShip.getHeight() * 2);
buyIShip.setLocation(getWidth() - buyIShip.getWidth(), buyIShip.getHeight() * 4);
buyUShip.setLocation(getWidth() - buyUShip.getWidth(), buyUShip.getHeight() * 6);
buyAShip.setLocation(getWidth() - buyAShip.getWidth(), buyAShip.getHeight() * 8);
buyCookieShip.setLocation(getWidth() - buyCookieShip.getWidth(), buyCookieShip.getHeight() * 10);
buyTShip.setLocation(getWidth() - buyTShip.getWidth(), buyTShip.getHeight() * 12);
cashButton.setLocation(getWidth() / 2 - cashButton.getWidth() / 2, 10);
testButton.setLocation(getWidth() / 2 - testButton.getWidth() / 2, testButton.getHeight() + 20);
sellHplus.setLocation(5, 200);
hBeingSold.setLocation(sellHplus.getWidth() + 20, 200);
sellHminus.setLocation(sellHplus.getWidth() + hBeingSold.getWidth() + 40, 200);
sellCplus.setLocation(5, 250);
cBeingSold.setLocation(sellCplus.getWidth() + 20, 250);
sellCminus.setLocation(sellCplus.getWidth() + cBeingSold.getWidth() + 40, 250);
sellIplus.setLocation(5, 300);
iBeingSold.setLocation(sellIplus.getWidth() + 20, 300);
sellIminus.setLocation(sellIplus.getWidth() + iBeingSold.getWidth() + 40, 300);
sellUplus.setLocation(5, 350);
uBeingSold.setLocation(sellUplus.getWidth() + 20, 350);
sellUminus.setLocation(sellUplus.getWidth() + uBeingSold.getWidth() + 40, 350);
sellAplus.setLocation(5, 400);
aBeingSold.setLocation(sellAplus.getWidth() + 20, 400);
sellAminus.setLocation(sellAplus.getWidth() + aBeingSold.getWidth() + 40, 400);
sellCookieplus.setLocation(5, 450);
cookiesBeingSold.setLocation(sellCookieplus.getWidth() + 20, 450);
sellCookieminus.setLocation(sellCookieplus.getWidth() + cookiesBeingSold.getWidth() + 40, 450);
}
public void playGame() {
for (int i = 0; i < sectors.size(); i++) {
hIncome = sectors.get(i).getStation().gethShip() - tradeH;
cIncome = sectors.get(i).getStation().getcShip() - tradeC;
iIncome = sectors.get(i).getStation().getiShip() - tradeI;
uIncome = sectors.get(i).getStation().getuShip() - tradeU;
aIncome = sectors.get(i).getStation().getaShip() - tradeA;
cookieIncome = sectors.get(i).getStation().getcChip() - tradeCookie;
cashIncome = (tradeH * 5) + (tradeC * 20) + (tradeI * 100)
+ (tradeU * 500) + (tradeA * 1500) + (tradeCookie * 5000);
}
for (int i = 0; i < sectors.size(); i++) {
spaceCash += cashIncome;
energy += energyIncome;
hydrogen += hIncome;
carbon += cIncome;
iron += iIncome;
uranium += uIncome;
antimatter += aIncome;
cookies += cookieIncome;
}
}
There's the code (excluding the action listener and initialization of variables and buttons).
Painting methods are for painting only:
Don't invoke methods like setText(....)
Don't invoke methods like setLocation()
Changing properties on a component will cause the component to be repainted which may cause an infinite loop.
Don't invoke super.paintComponent() in the drawItems() method. You should never invoke a painting method directly except to invoke super.paintComponent() in the paintComponent() method.
The playGame() method should not be invoked from the paintComponent() method. Again that is logic for your game. That code should be invoked from your Timer that controls the game.

Categories

Resources