Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 3 of 3

Thread: Help with an error in code

  1. #1
    Junior Member
    Join Date
    Dec 2010
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Help with an error in code

    I am a newbie to the java world. Can you please assist me by telling me why I am getting this error in my code. I know I am missing something but cant figure it out. The error is in the line when I use :

    volumeField.setText(df.format(volume)); The error is df cannot be resolved. I'd appreciate any help that you can give.

    import java.awt.Color;
    import java.awt.Container;
    import java.awt.FlowLayout;
    import java.awt.Font;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.awt.event.ItemEvent;
    import java.awt.event.ItemListener;
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.File;
    import java.io.FileReader;
    import java.io.FileWriter;
    import java.io.IOException;
    import java.text.DecimalFormat;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
     
    import javax.swing.BorderFactory;
    import javax.swing.ButtonGroup;
    import javax.swing.JButton;
    import javax.swing.JComboBox;
    import javax.swing.JDialog;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JRadioButton;
    import javax.swing.JScrollPane;
    import javax.swing.JTabbedPane;
    import javax.swing.JTextArea;
    import javax.swing.JTextField;
    public class LandScape {
     
    	/**
    	 * Application starts here.
    	 */
    	public static void main(String[] args) {
    	new LandScape ();
    	}
    		class Landscape extends JFrame{
    			private JTabbedPane tabs;
    			private JPanel generalPanel;			
    			private JPanel customersPanel;
    			private JPanel poolsPanel;
    			private JPanel hotTubsPanel;
     
    			private void initializeComponents() {
    				Container pane = getContentPane();
     
    				tabs = new JTabbedPane();
     
    				buildGeneralTab();
    				buildCustomersTab();
    				builPoolsTab();
    				buildHotTubsTab();
     
    				tabs.add("General", generalPanel);
    				tabs.add("Customers", customersPanel);
    				tabs.add("Pools", poolsPanel);
    				tabs.add("Hot Tubs", hotTubsPanel);
     
    				pane.add(tabs);
    			}
     
    			private void buildHotTubsTab() {
    				hotTubsPanel = new JPanel(new FlowLayout());
     
    				final JRadioButton roundTub = new JRadioButton("Round Tub");
    				final JRadioButton ovalTub = new JRadioButton("Oval Tub");
     
    				roundTub.setSelected(true);
     
    				ButtonGroup group = new ButtonGroup();
    				group.add(roundTub);
    				group.add(ovalTub);
     
    				hotTubsPanel.add(roundTub);
    				hotTubsPanel.add(ovalTub);
     
    				hotTubsPanel.add(new JLabel("Enter the tub's length (ft): "));
    				final JTextField lengthField = new JTextField(10);
    				hotTubsPanel.add(lengthField);
     
    				final JLabel widthLabel = new JLabel("Enter the tub's width (ft): ");
    				widthLabel.setEnabled(false);
    				hotTubsPanel.add(widthLabel);
     
    				final JTextField widthField = new JTextField(10);
    				widthField.setEnabled(false);
    				hotTubsPanel.add(widthField);
     
    				hotTubsPanel.add(new JLabel("Enter the tub's depth (ft): "));
    				final JTextField depthField = new JTextField(10);
    				hotTubsPanel.add(depthField);
     
    				JButton calculateVolume = new JButton("Calculate Volume");
    				calculateVolume.setMnemonic('C');
    				hotTubsPanel.add(calculateVolume);
    				hotTubsPanel.add(createExitButton());
     
    				hotTubsPanel.add(new JLabel("The tub's volume is (ft^3): "));
    				final JTextField volumeField = new JTextField(10);
    				volumeField.setEditable(false);
    				hotTubsPanel.add(volumeField);
     
    				final JTextArea messageArea = createMessageArea(1, 25,
    						"Width will be set to the same value as length");
    				hotTubsPanel.add(messageArea);
     
    				calculateVolume.addActionListener(new ActionListener() {
    					public void actionPerformed(ActionEvent e) {
    						if (roundTub.isSelected()) {
    							widthField.setText(lengthField.getText());
    						}
     
    						ValidationResult result = validateFields(new JTextField[] {
    								lengthField, widthField, depthField });
     
    						String errors = "";
    						if (result.filled != 3) {
    							errors += "Please fill out all fields! ";
    						}
    						if (result.valid != 3 && result.filled != result.valid) {
    							errors += "Please enter valid numbers!";
    						}
     
    						if (errors != "") {
    							messageArea.setText(errors);
    							messageArea.setVisible(true);
    						} else {
    							messageArea.setVisible(false);
     
    							double length = Double.parseDouble(lengthField.getText());
    							double width = Double.parseDouble(widthField.getText());
    							double depth = Double.parseDouble(depthField.getText());
     
    							double volume;
    							if (roundTub.isSelected()) {
    								volume = Math.PI * Math.pow(length / 2.0, 2) * depth;
    							} else {
    								volume = Math.PI * Math.pow(length * width, 2) * depth;
    							}
    							volumeField.setText(df.format(volume));
    						}
    					}
    				});
     
    				ActionListener tubsListener = new ActionListener() {
    					public void actionPerformed(ActionEvent e) {
    						if (e.getSource() == roundTub) {
    							widthLabel.setEnabled(false);
    							widthField.setEnabled(false);
    							widthField.setText(lengthField.getText());
    							messageArea.setText("Tub's width set to length");
    							messageArea.setVisible(true);
    						} else if (e.getSource() == ovalTub) {
    							widthLabel.setEnabled(true);
    							widthField.setEnabled(true);
    							messageArea.setVisible(false);
    						}
    					}
    				};
    				roundTub.addActionListener(tubsListener);
    				ovalTub.addActionListener(tubsListener);
    			}
     
    			private void builPoolsTab() {
    				poolsPanel = new JPanel(new FlowLayout());
     
    				poolsPanel.add(new JLabel("Enter the pool's length (ft): "));
    				final JTextField lengthField = new JTextField(10);
    				poolsPanel.add(lengthField);
     
    				poolsPanel.add(new JLabel("Enter the pool's width (ft): "));
    				final JTextField widthField = new JTextField(10);
    				poolsPanel.add(widthField);
     
    				poolsPanel.add(new JLabel("Enter the pool's depth (ft): "));
    				final JTextField depthField = new JTextField(10);
    				poolsPanel.add(depthField);
     
    				JButton calculateVolume = new JButton("Calculate Volume");
    				calculateVolume.setMnemonic('C');
    				poolsPanel.add(calculateVolume);
    				poolsPanel.add(createExitButton());
     
    				poolsPanel.add(new JLabel("The pool's volume is (ft^3): "));
    				final JTextField volumeField = new JTextField(10);
    				volumeField.setEditable(false);
    				poolsPanel.add(volumeField);
     
    				final JTextArea messageArea = createMessageArea(2, 20, "");
    				poolsPanel.add(messageArea);
     
    				calculateVolume.addActionListener(new ActionListener() {
    					public void actionPerformed(ActionEvent e) {
    						ValidationResult result = validateFields(new JTextField[] {
    								lengthField, widthField, depthField });
     
    						String errors = "";
    						if (result.filled != 3) {
    							errors += "Please fill out all fields! ";
    						}
    						if (result.valid != 3 && result.filled != result.valid) {
    							errors += "Please enter valid numbers!";
    						}
     
    						if (errors != "") {
    							messageArea.setText(errors);
    							messageArea.setVisible(true);
    						} else {
    							messageArea.setVisible(false);
     
    							double length = Double.parseDouble(lengthField.getText());
    							double width = Double.parseDouble(widthField.getText());
    							double depth = Double.parseDouble(depthField.getText());
     
    							double volume = length * width * depth;
     
    							volumeField.setText(df.format(volume));
    						}
    					}
    				});
    			}
     
     
     
     
     
    			private void buildCustomersTab() {
    				customersPanel = createContactPanel("Customer", "customer.txt");
    			}
     
     
     
     
     
     
    			private void buildGeneralTab() {
    				generalPanel = new JPanel(new FlowLayout());
    				String currentTime = SimpleDateFormat.getInstance().format(
    						Calendar.getInstance().getTime());
    				generalPanel.add(new JLabel("Today's Date: " + currentTime));
    				generalPanel.add(createExitButton());
    			}
     
     
    			private JButton createExitButton() {
    				JButton exitButton = new JButton("Exit");
    				exitButton.setMnemonic('x');
    				exitButton.addActionListener(new ActionListener() {
    					public void actionPerformed(ActionEvent e) {
    						System.exit(0);
    					}
    				});
    				return exitButton;
    			}
     
     
    			@SuppressWarnings("unused")
    			private JTextField createTitleField(String text, int length) {
    				JTextField tf = new JTextField(length);
    				tf.setEditable(false);
    				tf.setFocusable(false);
    				tf.setText(text);
    				return tf;
    			}
     
     
    			private String loadDataFromFile(String fileName) {
    				String data = "";
     
    				try {
    					BufferedReader reader = new BufferedReader(new FileReader(fileName));
    					while (reader.ready()) {
    						data += reader.readLine() + "\n";
    					}
    					reader.close();
    				} catch (IOException e) {
    				}
     
    				return data;
    			}
     
     
    			private JPanel createContactPanel(final String contactName,
    					final String fileName) {
     
    				JPanel pane = new JPanel(new FlowLayout());
     
    				final JTextArea customerDisplay = new JTextArea(8, 25);
    				customerDisplay.setLineWrap(true);
    				customerDisplay.setEditable(false);
    				pane.add(new JScrollPane(customerDisplay));
     
    				pane.add(createExitButton());
     
    				JButton addCustomerButton = new JButton("Add " + contactName);
    				addCustomerButton.setMnemonic('A');
    				pane.add(addCustomerButton);
     
    				JButton refreshButton = new JButton("Refresh");
    				refreshButton.setMnemonic('R');
    				pane.add(refreshButton);
     
    				final JTextArea messageArea = createMessageArea(2, 25, "");
    				pane.add(messageArea);
     
    				addCustomerButton.addActionListener(new ActionListener() {
    					public void actionPerformed(ActionEvent e) {
    						new EditContact(contactName, fileName);
    					}
    				});
     
    				refreshButton.addActionListener(new ActionListener() {
    					public void actionPerformed(ActionEvent e) {
    						String data = loadDataFromFile(fileName);
    						if (data != "") {
    							customerDisplay.setText(data);
    							customerDisplay.setEnabled(true);
    							messageArea.setText("File " + fileName + " exists "
    									+ "and can be read from!");
    						} else {
    							customerDisplay.setText("Select Add " + contactName
    									+ " to add " + contactName.toLowerCase()
    									+ "s. Select Refresh to refresh this pane.");
    							customerDisplay.setEnabled(false);
    							messageArea.setText("File " + fileName + " does not "
    									+ "exist yet! Will be created " + "when you add "
    									+ contactName.toLowerCase() + "s!");
    						}
    					}
    				});
     
    				refreshButton.doClick();
     
    				return pane;
    			}
     
     
    			private JTextArea createMessageArea(int rows, int cols, String text) {
    				final JTextArea messageArea = new JTextArea(rows, cols);
    				messageArea.setBorder(BorderFactory.createEmptyBorder());
    				messageArea.setLineWrap(true);
    				messageArea.setWrapStyleWord(true);
    				messageArea.setFont(new Font("System", Font.PLAIN, 12));
    				messageArea.setText(text);
    				messageArea.setBackground(null);
    				messageArea.setForeground(Color.red);
    				messageArea.setEnabled(true);
    				messageArea.setFocusable(false);
    				return messageArea;
    			}
     
     
    			private class ValidationResult {
    				/** Number of non-empty fields */
    				int filled;
    				/** Number of valid fields */
    				int valid;
    			}
     
     
    			private ValidationResult validateFields(JTextField[] fields) {
    				ValidationResult result = new ValidationResult();
    				for (int i = 0; i < fields.length; i++) {
    					JTextField field = fields[i];
    					if ((field.getText() != null) && (field.getText().length() > 0)) {
    						result.filled++;
    					}
    					try {
    						Double.parseDouble(field.getText());
    						field.setBackground(Color.white);
    						result.valid++;
    					} catch (Exception e) {
    						field.setBackground(Color.orange);
    					}
    				}
    				return result;
    			}
     
     
    			private class EditContact extends JDialog {
    				private final String contactName;
    				private final String fileName;
    				private File file;
     
    				private JTextField nameField;
    				private JTextField addressField;
    				private JTextField cityField;
    				private JComboBox stateComboBox;
    				private JTextField zipField;
    				private JTextField phoneField;
    				private JTextArea messageArea;
     
     
    				public EditContact(String contactName, String fileName) {
    					super(Landscape.this, contactName + "s");
    					setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
    					setModalityType(ModalityType.APPLICATION_MODAL);
    					setSize(400, 300);
    					this.contactName = contactName;
    					this.fileName = fileName;
     
    					initializeComponents();
     
    					if (openFile()) {
    						displayMessage(null);
    					} else {
    						displayMessage("File " + fileName + " does not exist yet! "
    								+ "Will be created when you add a "
    								+ contactName.toLowerCase() + "!");
    					}
     
    					setLocationRelativeTo(null);
    					setVisible(true);
    				}
     
    				private void displayMessage(String message) {
    					if (message != null) {
    						messageArea.setVisible(true);
    						messageArea.setText(message);
    					} else {
    						messageArea.setVisible(false);
    					}
    				}
     
    				private boolean openFile() {
    					file = new File(fileName);
    					return file.exists();
    				}
     
    				private boolean deleteFile() {
    					return file.exists() && file.delete();
    				}
     
    				private boolean saveToFile() {
    					try {
    						BufferedWriter writer = new BufferedWriter(new FileWriter(file,
    								true));
     
    						writer.write("Name: " + nameField.getText() + "\n");
    						writer.write("Address: " + addressField.getText() + "\n");
    						writer.write("City: " + cityField.getText() + "\n");
    						writer.write("State: "
    								+ stateComboBox.getSelectedItem().toString() + "\n");
    						writer.write("ZIP: " + zipField.getText() + "\n");
    						writer.write("Phone: " + phoneField.getText() + "\n");
    						writer.write("\n");
     
    						writer.close();
    						return true;
     
    					} catch (IOException e) {
    						return false;
    					}
    				}
     
    				private void initializeComponents() {
    					Container pane = getContentPane();
    					pane.setLayout(new FlowLayout());
     
    					pane.add(new JLabel(contactName + " Name "));
    					nameField = new JTextField(25);
    					pane.add(nameField);
     
    					pane.add(new JLabel("Address "));
    					addressField = new JTextField(28);
    					pane.add(addressField);
     
    					pane.add(new JLabel("City "));
    					cityField = new JTextField(32);
    					pane.add(cityField);
     
    					pane.add(new JLabel("State "));
    					stateComboBox = new JComboBox(new String[] { "AL", "AK", "AZ",
    							"AR", "CA", "CO", "CT", "DE", "FL", "GA", "HI", "ID", "IL",
    							"IN", "IA", "KS", "KY", "LA", "ME", "MD", "MA", "MI", "MN",
    							"MS", "MO", "MT", "NE", "NV", "NH", "NJ", "NM", "NY", "NC",
    							"ND", "OH", "OK", "OR", "PA", "RI", "SC", "SD", "TN", "TX",
    							"UT", "VT", "VA", "WA", "WV", "WI", "WY" });
    					pane.add(stateComboBox);
     
    					pane.add(new JLabel("ZIP "));
    					zipField = new JTextField(5);
    					pane.add(zipField);
     
    					pane.add(new JLabel("Phone "));
    					phoneField = new JTextField(10);
    					pane.add(phoneField);
     
    					JButton addContactButton = new JButton("Add " + this.contactName);
    					addContactButton.setMnemonic('A');
    					addContactButton.addActionListener(new ActionListener() {
    						public void actionPerformed(ActionEvent e) {
    							if (saveToFile()) {
    								displayMessage(contactName + " added");
    							} else {
    								displayMessage("File saving error!");
    							}
    						}
    					});
    					pane.add(addContactButton);
     
    					JButton closeButton = new JButton("Close");
    					closeButton.setMnemonic('C');
    					closeButton.addActionListener(new ActionListener() {
    						public void actionPerformed(ActionEvent e) {
    							setVisible(false);
    						}
    					});
    					pane.add(closeButton);
     
    					JButton deleteFileButton = new JButton("Delete File");
    					deleteFileButton.setMnemonic('D');
    					deleteFileButton.addActionListener(new ActionListener() {
    						public void actionPerformed(ActionEvent e) {
    							if (deleteFile()) {
    								displayMessage("File " + fileName + " deleted!");
    							}
    						}
    					});
    					pane.add(deleteFileButton);
     
    					messageArea = createMessageArea(2, 30, "");
    					pane.add(messageArea);
    				}
    			}
    		}}


  2. #2
    Banned
    Join Date
    May 2010
    Location
    North Central Illinois
    Posts
    1,631
    My Mood
    Sleepy
    Thanks
    390
    Thanked 112 Times in 110 Posts

    Default Re: Help with an error in code

    First of all, this is the Member Introductions forum. You're looking for What's Wrong With My Code? - Java Programming Forums

    Also, you never defined df nor did you initialize it.

    Even if you did, though I didn't come across it, it's probably lost when it went out of scope if you defined it inside a method.

    You probably might have meant depthfield

  3. #3
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,318
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: Help with an error in code

    Thread moved to What's Wrong With My Code?

Similar Threads

  1. Error with code
    By JJTierney in forum What's Wrong With My Code?
    Replies: 1
    Last Post: December 4th, 2010, 05:23 PM
  2. Replies: 1
    Last Post: May 12th, 2010, 08:54 AM
  3. Replies: 1
    Last Post: March 31st, 2010, 09:42 PM
  4. help me out with the following code to solve the error
    By romilc in forum What's Wrong With My Code?
    Replies: 1
    Last Post: October 11th, 2009, 03:45 AM