Variable will not set...

Ok, so I'm making this program for my school counselor to convert credits from other schools to our credit system. Everything works great until I try and print the document with the information on it. For some reason the variables I'm using for the math have their values set everywhere except in the method that I'm using to print them. Here is the code I'm setting them with:

creditsEarned = ((Number)creditsEarnedField.getValue()).doubleValue();

System.out.println(String.valueOf(creditsEarned));

and here is the code that I'm using to print them when they click on the "Print" button.

menuItem.addActionListener(new ActionListener()

{

publicvoid actionPerformed(ActionEvent k)

{

//WordProcessing.createNewDocumentFromTemplate("creditConversion");

//WordProcessing.typeTextAtBookmark("studentName", studentName);

System.out.println(String.valueOf(studentName));

//WordProcessing.typeTextAtBookmark("studentNumber", studentNumber);

System.out.println(String.valueOf(studentNumber));

//WordProcessing.typeTextAtBookmark("creditsEarned", creditsEarned);

System.out.println(String.valueOf(creditsEarned));

//WordProcessing.typeTextAtBookmark("remainingCredits", ARHSCredits);

System.out.println(String.valueOf(ARHSCredits));

//WordProcessing.typeTextAtBookmark("totalCreditsNeeded", creditTotal);

//WordProcessing.printToPrinterToSelectByUserAndForget();

//WordProcessing.quitApplication();

//WordProcessing.exec();

System.out.println(getCredits());

}

});

When I print them out in the DOS screen they all have the right values when I print them after I set them.(first code segment) But when I print them when the "Print" button is pressed they all return as null, 0, or 0.0 :confused: (depending on their type). Any help is greatly appreciated and thanks in advance. Feel free to ask any questions if I haven't been clear enough.

[2469 byte] By [EmBraCea] at [2007-10-2 13:56:12]
# 1

How do we get from here:

creditsEarned = ((Number)creditsEarnedField.getValue()).doubleValue();

System.out.println(String.valueOf(creditsEarned));

... to here:and here is the code that I'm using to print them when they click on the "Print" button.

menuItem.addActionListener(new ActionListener()

{

public void actionPerformed(ActionEvent k)

abillconsla at 2007-7-13 12:00:11 > top of Java-index,Java Essentials,Java Programming...
# 2
Probably because you defined class variable and local variable with the same name. So the method where you set the local variable appears correct, but all other methods will reference the class variable which still have there default values.
camickra at 2007-7-13 12:00:11 > top of Java-index,Java Essentials,Java Programming...
# 3

All my variables are instanciated at the class level and never redefined as a local variable, thats what really boggled my mind when I was looking through all my code. My teacher is confused as well, would like to see the entire code? I may just be flat our missing something completely obvious...

EmBraCea at 2007-7-13 12:00:11 > top of Java-index,Java Essentials,Java Programming...
# 4
@abillconsl: I was showing you how I set the variables and how I returned them, but I forgot to show that they were in different methods. My bad on not clarifying that if thats what confused you.
EmBraCea at 2007-7-13 12:00:11 > top of Java-index,Java Essentials,Java Programming...
# 5

> @abillconsl: I was showing you how I set the

> variables and how I returned them, but I forgot to

> show that they were in different methods. My bad on

> not clarifying that if thats what confused you.

Yes, what I meant was that you leave no way to connect the two uses of the variables or sets of variables. How do we know that comickr is not right?

abillconsla at 2007-7-13 12:00:11 > top of Java-index,Java Essentials,Java Programming...
# 6

The first code section is in a propertChange method and takes the value of the field that is the source of the change and inputs it into the variable, which was defined at the class level. I then call on an actionListener in a menu item, that is created in a createMenu method, that will print those very same variables. Only problem is they are empty... but only when called on in that method. When I was error checking I added SOP's to the method that computes the math and they returned fine. I am at home now and the code is at school so if you want a full code showing it would have to wait til monday.

EmBraCea at 2007-7-13 12:00:11 > top of Java-index,Java Essentials,Java Programming...
# 7
Anyone else help? Let me know if you need to see all the code, I have it with me now.
EmBraCea at 2007-7-13 12:00:11 > top of Java-index,Java Essentials,Java Programming...
# 8

If the variables are empty, one of the following must be true

1. The variables were never set to anything;

2. The vairables were not set to anything prior to being checked;

3. The variables were reset to null, prior to being checked;

4. The variables being set are not the same ones being checked; not the ones you think they are;

5. The vairables are obscured (to you) by more local ones (this is more specific than 4, above);

I can't think of any other reasons, and in fact I think these were already mentioned by others - did not go back to reread post - but your problem is almost certainly one of the above.

abillconsla at 2007-7-13 12:00:11 > top of Java-index,Java Essentials,Java Programming...
# 9

package de.must.util;

import java.awt.*;

import java.awt.event.*;

import java.io.*;

import java.applet.*;

import javax.swing.*;

import javax.swing.event.*;

import javax.swing.text.*;

import java.beans.PropertyChangeListener;

import java.beans.PropertyChangeEvent;

import java.text.*;

import java.math.*;

import javax.swing.table.*;

public class CreditConversion extends JPanel

implements PropertyChangeListener

{

//Values for the fields

private double creditsEarned;

private double outOf, ARHSCredits, creditTotal;

private int studentNumber;

private double gradeLevel;

private String studentName;

JButton calcButton = null;

private static final boolean noteNotMatchingBookmarks = true;

JCheckBox halfButton;

private static boolean isFullScreen = false;

private static GraphicsDevice device;

//Labels to identify the fields

private JLabel studentNumberLabel;

private JLabel studentNameLabel;

private JLabel creditTotalLabel;

private JLabel creditsEarnedLabel;

private JLabel outOfLabel;

private JLabel gradeLevelLabel;

private JLabel ARHSCreditsLabel;

//String for the labels

private String[] classStrings = {"1/2 Freshmen", "Freshmen","Sophmore","Junior","Senior"};

private String studentNumberString = "Student Number: ";

private String studentNameString = "Student Name: ";

private String creditTotalString = "ARHS Total Credits: ";

private static String creditsEarnedString = "Credits Earned: ";

private static String outOfString = "Credits Possible: ";

private static String gradeLevelString = "Grade Level at ARHS: ";

private static String ARHSCreditsString = "Credits Needed to Graduate: ";

//Fields for data entry

private JFormattedTextField studentNumberField;

private JFormattedTextField studentNameField;

private JFormattedTextField creditTotalField;

private JFormattedTextField creditsEarnedField;

private JFormattedTextField outOfField;

private JFormattedTextField gradeLevelField;

private JFormattedTextField ARHSCreditsField;

//Formats to format and parse numbers

private NumberFormat studentNameFormat;

private NumberFormat studentNumberFormat;

private NumberFormat creditTotalFormat;

private NumberFormat creditsEarnedFormat;

private NumberFormat outOfFormat;

private NumberFormat ARHSCreditsFormat;

public CreditConversion(JFrame frame)

{

super(new BorderLayout());

double creditsNeeded = computeCredits(creditsEarned, outOf, gradeLevel);

calcButton = new JButton("Calculate");

halfButton = new JCheckBox("Half a Year?");

halfButton.setSelected(false);

JComboBox classList = new JComboBox(classStrings);

creditTotalFormat = NumberFormat.getNumberInstance();

creditTotalFormat.setMaximumFractionDigits(1);

ARHSCreditsFormat = NumberFormat.getNumberInstance();

ARHSCreditsFormat.setMaximumFractionDigits(1);

//Create the labels.

studentNameLabel = new JLabel(studentNameString);

studentNumberLabel = new JLabel(studentNumberString);

creditTotalLabel = new JLabel(creditTotalString);

creditsEarnedLabel = new JLabel(creditsEarnedString);

outOfLabel = new JLabel(outOfString);

gradeLevelLabel = new JLabel(gradeLevelString);

ARHSCreditsLabel = new JLabel(ARHSCreditsString);

//Create the text fields and set them up.

studentNameField = new JFormattedTextField(studentNameFormat);

studentNameField.setValue(studentName);

studentNameField.setColumns(10);

studentNameField.addPropertyChangeListener("value", this);

studentNumberField = new JFormattedTextField(studentNumberFormat);

studentNumberField.setValue(new Integer(studentNumber));

studentNumberField.setColumns(10);

studentNumberField.addPropertyChangeListener("value", this);

creditsEarnedField = new JFormattedTextField(creditsEarnedFormat);

creditsEarnedField.setValue(new Double(creditsEarned));

creditsEarnedField.setColumns(10);

creditsEarnedField.addPropertyChangeListener("value", this);

outOfField = new JFormattedTextField(outOfFormat);

outOfField.setValue(new Double(outOf));

outOfField.setColumns(10);

outOfField.addPropertyChangeListener("value", this);

gradeLevelField = new JFormattedTextField();

gradeLevelField.setValue(new Integer(9));

gradeLevelField.setColumns(10);

gradeLevelField.addPropertyChangeListener("value", this);

ARHSCreditsField = new JFormattedTextField(ARHSCreditsFormat);

ARHSCreditsField.setValue(new Double(creditsNeeded));

ARHSCreditsField.setColumns(10);

ARHSCreditsField.setEditable(false);

ARHSCreditsField.setBackground(Color.black);

ARHSCreditsField.setForeground((Color.red));

creditTotalField = new JFormattedTextField(creditTotalFormat);

creditTotalField.setValue(new Double(creditTotal));

creditTotalField.setColumns(10);

creditTotalField.setEditable(false);

creditTotalField.setBackground(Color.black);

creditTotalField.setForeground((Color.cyan).darker());

//Tell accessibility tools about label/textfield pairs.

studentNameLabel.setLabelFor(creditsEarnedField);

studentNumberLabel.setLabelFor(creditsEarnedField);

creditTotalLabel.setLabelFor(creditTotalField);

creditsEarnedLabel.setLabelFor(creditsEarnedField);

outOfLabel.setLabelFor(outOfField);

gradeLevelLabel.setLabelFor(gradeLevelField);

ARHSCreditsLabel.setLabelFor(ARHSCreditsField);

//Lay out the labels in a panel.

JPanel labelPane = new JPanel(new GridLayout(0,1));

labelPane.add(studentNameLabel);

labelPane.add(studentNumberLabel);

labelPane.add(creditsEarnedLabel);

labelPane.add(outOfLabel);

labelPane.add(gradeLevelLabel);

labelPane.add(ARHSCreditsLabel);

labelPane.add(creditTotalLabel);

//Layout the text fields in a panel.

JPanel fieldPane = new JPanel(new GridLayout(0,1));

fieldPane.add(studentNameField);

fieldPane.add(studentNumberField);

fieldPane.add(creditsEarnedField);

fieldPane.add(outOfField);

fieldPane.add(classList);

fieldPane.add(halfButton);

fieldPane.add(ARHSCreditsField);

fieldPane.add(creditTotalField);

//Put the panels in this panel, labels on left,

//text fields on right.

setBorder(BorderFactory.createEmptyBorder(40, 40, 20, 20));

add(labelPane, BorderLayout.CENTER);

add(fieldPane, BorderLayout.LINE_END);

//add(halfButton, BorderLayout.NORTH);

add(calcButton, BorderLayout.SOUTH);

calcButton.addActionListener(new ActionListener()

{

public void actionPerformed(ActionEvent e)

{

ARHSCredits = computeCredits(creditsEarned, outOf, gradeLevel);

ARHSCreditsField.setValue(new Double(ARHSCredits));

creditTotalField.setValue(new Double(creditTotal));

System.out.println(getCredits());

return;

}

});

halfButton.addActionListener(new ActionListener()

{

public void actionPerformed(ActionEvent e)

{

if(halfButton.isSelected() == true)

gradeLevel = (gradeLevel + (.5));

else

gradeLevel = (gradeLevel - (.5));

}

});

classList.addActionListener(new ActionListener()

{

public void actionPerformed(ActionEvent e)

{

JComboBox cb = (JComboBox)e.getSource();

gradeLevel = cb.getSelectedIndex();

}

});

}

public JMenuBar createMenuBar()

{

JMenuBar menuBar;

JMenu menu;

JMenuItem menuItem, menuItem2;

//Create the menu bar.

menuBar = new JMenuBar();

//Build the first menu.

menu = new JMenu("File");

menu.setMnemonic(KeyEvent.VK_A);

menu.getAccessibleContext().setAccessibleDescription(

"");

menuBar.add(menu);

menuItem2 = new JMenuItem("New",

KeyEvent.VK_N);

menuItem2.setAccelerator(KeyStroke.getKeyStroke(

KeyEvent.VK_1, ActionEvent.ALT_MASK));

menuItem = new JMenuItem("Print",

KeyEvent.VK_P);

menuItem.setAccelerator(KeyStroke.getKeyStroke(

KeyEvent.VK_2, ActionEvent.ALT_MASK));

menu.add(menuItem2);

menu.add(menuItem);

menuItem.addActionListener(new ActionListener()

{

public void actionPerformed(ActionEvent k)

{

//WordProcessing.createNewDocumentFromTemplate("creditConversion");

//WordProcessing.typeTextAtBookmark("studentName", studentName);

System.out.println(studentName);

//WordProcessing.typeTextAtBookmark("studentNumber", studentNumber);

System.out.println(studentNumber);

//WordProcessing.typeTextAtBookmark("creditsEarned", creditsEarned);

System.out.println(creditsEarned);

//WordProcessing.typeTextAtBookmark("remainingCredits", ARHSCredits);

System.out.println(ARHSCredits);

//WordProcessing.typeTextAtBookmark("totalCreditsNeeded", creditTotal);

//WordProcessing.printToPrinterToSelectByUserAndForget();

//WordProcessing.quitApplication();

//WordProcessing.exec();

System.out.println(getCredits());

}

});

/*menuItem2.addActionListener(new ActionListener()

{

public void actionPerformed(ActionEvent k)

{

Double nothing = new Double(0.0);

creditsEarned = 0.0;

creditsEarnedField.setValue(nothing);

outOf = 0.0;

outOfField.setValue(nothing);

ARHSCredits = 0.0;

ARHSCreditsField.setValue(nothing);

creditTotal = 0.0;

creditTotalField.setValue(nothing);

studentNumber = 0;

studentNumberField.setValue(new Integer(0));

gradeLevel = 0.0;

studentName = "";

studentNameField.setValue("");

}

});*/

return menuBar;

}

/** Called when a field's "value" property changes. */

public void propertyChange(PropertyChangeEvent e)

{

Object source = e.getSource();

if (source == creditsEarnedField)

{

creditsEarned = ((Number)creditsEarnedField.getValue()).doubleValue();

System.out.println(String.valueOf(creditsEarned));

}

else if (source == outOfField)

{

outOf = ((Number)outOfField.getValue()).doubleValue();

System.out.println(String.valueOf(outOf));

}

else if (source == studentNameField)

{

studentName = ((String)studentNameField.getValue());

System.out.println(studentName);

}

else if (source == studentNumberField)

{

studentNumber = ((Number)studentNumberField.getValue()).intValue();

System.out.println(String.valueOf(studentNumber));

}

}

private static void createAndShowGUI()

{

/*GraphicsEnvironment env = GraphicsEnvironment.

getLocalGraphicsEnvironment();

GraphicsDevice device = env.getDefaultScreenDevice();

GraphicsConfiguration gc = device.getDefaultConfiguration();*/

JFrame.setDefaultLookAndFeelDecorated(false);

//Create and set up the window.

JFrame frame = new JFrame("ARHS Credit Conversion");

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

//Create and set up the content pane.

JComponent newContentPane = new CreditConversion(frame);

newContentPane.setOpaque(true); //content panes must be opaque

frame.setContentPane(newContentPane);

CreditConversion list = new CreditConversion(frame);

frame.setJMenuBar(list.createMenuBar());

/*frame.setUndecorated(true);

frame.setIgnoreRepaint(false);

device.setFullScreenWindow(frame);*/

//Display the window.

frame.pack();

frame.setVisible(true);

}

public static void main(String[] args)

{

//Schedule a job for the event-dispatching thread:

//creating and showing this application's GUI.

javax.swing.SwingUtilities.invokeLater(new Runnable()

{

public void run()

{

createAndShowGUI();

}

});

}

public double getCredits()

{

return creditTotal;

}

public double computeCredits(double myCreditsEarned, double myOutOf, double myGradeLevel)

{

double creditPercent, arhsCredits, arhsCreditsPossible=0, neededCredits=0.0;

if(myGradeLevel==0)

arhsCreditsPossible = 3;

else if(myGradeLevel==1)

arhsCreditsPossible = 6;

else if(myGradeLevel==1.5)

arhsCreditsPossible = 9;

else if(myGradeLevel==2)

arhsCreditsPossible = 12;

else if(myGradeLevel==2.5)

arhsCreditsPossible = 15;

else if(myGradeLevel==3)

arhsCreditsPossible = 18;

else if(myGradeLevel==3.5)

arhsCreditsPossible = 21;

else if(myGradeLevel==4)

arhsCreditsPossible = 24;

creditPercent = (myCreditsEarned/myOutOf);

arhsCredits = (creditPercent*arhsCreditsPossible);

neededCredits = (22.50 - arhsCredits);

creditTotal = arhsCredits;

return neededCredits;

}

}

There it is, I must be having a brain ****(passing gas) cause after your last post I looked around at all my variable definitions and didn't see them getting reset. Although I think thats what happening but I'm just not seeing it. Gah, I feel like such a newb.... Also, I'm not near completion so this probably isn't the most efficient program on he planet but I hope to make it much better.

EmBraCea at 2007-7-13 12:00:11 > top of Java-index,Java Essentials,Java Programming...
# 10

I didn't look at your code in detail, but one thing jumped out at me that I would look into if it were my code.

One of the variables that you say is empty is a variable that is returned from computeCredits(...). In computeCredits(...) you have an if statement that could leave a value null (there is no default set a condition has be true or you don't set it to anything). You then use that value in a calculation whose result should be an Exception, but you are not checking for Exceptions, instead you return a value that appears to be undefined.

It might not be the problem, but like I said, if it was my code it is one place I would look.

Best of luck to you.

WorkForFooda at 2007-7-13 12:00:11 > top of Java-index,Java Essentials,Java Programming...
# 11
The "if" in computeCredits can't leave arhsCreditsPossible uninitialized. If it did, javac would complain. In that method, arhsCreditsPossible is explicitly initialized to 0 at declaration time.
MLRona at 2007-7-13 12:00:11 > top of Java-index,Java Essentials,Java Programming...
# 12
I don't think I see what your taking about. Which variable would be left at null? If it's arhsCreditsPossible then it would never be null as it is set to 0 when declared.
EmBraCea at 2007-7-13 12:00:11 > top of Java-index,Java Essentials,Java Programming...
# 13
Put the following line in your CreditConversion constructor:System.out.println("Constructing a new CreditConversion");Then re-run your program and see what happens. I know what your problem is.
MLRona at 2007-7-13 12:00:11 > top of Java-index,Java Essentials,Java Programming...
# 14

> The "if" in computeCredits can't leave

> arhsCreditsPossible uninitialized. If it did, javac

> would complain. In that method, arhsCreditsPossible

> is explicitly initialized to 0 at declaration time.

Yes, you抮e right; I missed the initialization. Now that we excluded this piece of code as the possible cause, where is the problem occurring?

To me, the code still looks unusual if nothing else, so I might do something like this just to validate it is doing what I expect, but don't waste your time if MLRon can pinpoint this for you. You may want to do something similar in other parts of your code where you are manipulating these values and variables.

try {

creditPercent = (myCreditsEarned/myOutOf);

System.out.println("CreditPrecent="+CreditPercent);

arhsCredits = (creditPercent*arhsCreditsPossible);

System.out.println("arhsCredits="+arhsCredits);

neededCredits = (22.50 - arhsCredits);

System.out.println("neededCredits="+neededCredits);

creditTotal = arhsCredits;

System.out.println("creditTotal="+creditTotal);

}

catch (Exception e) {

System.out.println("Exception=" + e.getMessage());

}

This is a perfect example of where an IDE with a debugger and watch function could save hours of time identifying where this problem is occurring (I抦 guessing less then a minute), rather then having to guess and then lace the code with System.out.println statements. But I'm guessing that is what you will have to do to figure this out (even if that function isn't causing this problem).

WorkForFooda at 2007-7-13 12:00:11 > top of Java-index,Java Essentials,Java Programming...
# 15
Just for the record, computeCredits doesn't have any errors in it, and is not causing the problem.
MLRona at 2007-7-20 22:06:56 > top of Java-index,Java Essentials,Java Programming...
# 16

//Create and set up the content pane.

JComponent newContentPane = new CreditConversion(frame);

newContentPane.setOpaque(true); //content panes must be opaque

frame.setContentPane(newContentPane);

CreditConversion list = new CreditConversion(frame);

frame.setJMenuBar(list.createMenuBar());

You create a CreditConverson panel with all your components to use as the content pane.

Then you create another CreditConversion panel and invoke the createMenuBar() method. This results in a second set of variables being created and referenced by the menu bar Action which will always be null since the panel is just sitting in memory and has not been added to the GUI.

Using your existing code you would just do:

CreditConversion newContentPane = new CreditConversion(frame);

// newContentPane.setOpaque(true); // not required, JPanel is opaque by default

frame.setContentPane(newContentPane);

frame.setJMenuBar(newContentPane.createMenuBar());

However, even this is not a good design. The menu bar is related to the JFrame, not the panel and should not be created from within the panel.

A simpler design is to create a class that extend JFrame. Then in the JFrame constructor you have code like:

setContentPane( createContentPane );

setJMenuBar( createJMenuBar );

camickra at 2007-7-20 22:06:56 > top of Java-index,Java Essentials,Java Programming...
# 17

I'll try yours in abit work but I tried MLRon's and it printed the SOP 2x and then null. The null is fromstudentName = ((String)studentNameField.getValue());

System.out.println(studentName);

because it starts in that box which triggers the SOP but with no input, once something is typed it prints the typed thing. But it being printed 2x means it''s being called on 2x. Interesting...

EmBraCea at 2007-7-20 22:06:56 > top of Java-index,Java Essentials,Java Programming...
# 18
camickr's reasoning is the same as mine--you have two CreditConversion instances. That's why I suggested that println--shows that the constructor ran twice.
MLRona at 2007-7-20 22:06:56 > top of Java-index,Java Essentials,Java Programming...
# 19
After posting my previous post then reading camickr's post I think I have the problem fixed Thanks everyone for the help, I can finally move on and try to make the code more efficient and of better design.
EmBraCea at 2007-7-20 22:06:56 > top of Java-index,Java Essentials,Java Programming...