1

I'm using CardLayout to develop a budget application. My code below creates a JPanel main_panel that houses a homepage JPanel card called "homePageCard" and another JPanel card called "addItemCard". When I click on the JButton "addItemButton" entitled "Add Item" it successfully takes me to the "addItemCard".

I also inserted a "previousButton" entitled "previous" to my "addItemCard" to take me back to the "homePageCard", added a "saveBudgetItem" button for the user to save his or her budget item data, and added 2 JTextFields: "budget_Item_Title_Field" and "budget_Amount_Field" to the "addItemCard". If you user tries to save the budget item by clicking on the JButton "saveBudgetItemButton" without filling out either of these two text fields (aka if either of the 2 fields contain empty Strings), the user should receive a JOptionPane error message dialog box. If the save is successful, another JOptionPane dialog box should tell the user the budget item was saved successfully.

Here's the crux of my problem: when I click on "previous" to get to the homepageCard and clear the text fields (within the action listener of the previous button), and then return to the addItemCard by pressing the "Add Item" button, it successfully clears both textfields by using budget_Item_Title_Field.setText("") and budget_Amount_Field.setText("").

However, when I type in new text for both text fields and click on the saveBudgetItem JButton, I incorrectly get the error message detailed below as a JOptionPane.showmessagedialog message, complaining that I still have empty Strings in either textfield when both fields are NOT empty.

How do I make it so that when I return to the addItemCard after clicking the "previous" button and type in a new budget item's title and amount in their respective textfields, the program recognizes that the updated textfields no longer contain empty Strings?

Here is my main class code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Main
{
    public static void main(String[] args)
    { 
        SwingUtilities.invokeLater(new Runnable() {
        public void run() {
           // Create main GUI to display and to use software, and add contents to it
           HomePage h = new HomePage();
        }});
    }
}

Here is my code for the HomePage class:

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;

public class HomePage extends JFrame {
    // Panel to contain contents of JFrame
    private static JPanel contentPanel = new JPanel(new BorderLayout());
    private static Dimension screenDimensions = Toolkit.getDefaultToolkit().getScreenSize();
    private static int screenWidth = screenDimensions.width;
    private static int screenHeight = screenDimensions.height;
    private static int frameWidth = 800;
    private static int frameHeight = 510;

    // the following are components for card layout and widgets for entering budget data
    private static JPanel main_panel = new JPanel(new CardLayout());
    private static JPanel homeCard = new JPanel(new BorderLayout());
    private static JPanel addItemCard = new JPanel(new BorderLayout());
    private static JPanel textfieldPanel = new JPanel(new FlowLayout());
    private static JTextField budget_Title_Field;
    private static JTextField amount_Field;
    private static JButton previous = new JButton("<< previous");
    private static JButton addItemButton = new JButton("Add Revenue or Expense");
    private static JButton saveBudgetItemButton = new JButton("Save Budget Item");

    public HomePage() {
        // format frame
        setSize(frameWidth, frameHeight);
        setResizable(false);
        setLocation((screenWidth - frameWidth) / 2, (screenHeight - frameHeight) / 2);
        setVisible(true);
        setDefaultCloseOperation(EXIT_ON_CLOSE);

        // format home page and add all cards to main_panel to manipulate them in card layout       
        formatHomeCard(homeCard);

        // add all cards to main_panel
        main_panel.add(homeCard, "Home");
        main_panel.add(addItemCard, "Add Item");

       // add main_panel to home JFrame
       this.add(main_panel);
    }

    public static void formatHomeCard(JPanel homeCard)
    {
        // Add functionality to addItemButton so it switches the card to the Add Item page
        addItemButton.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                // Adds all of the contents of the add revenue or expense page to the           
                // addItemCard
                formatAddItemCard(addItemCard);

                // If the add item button is pressed, switch the JPanel so that the add item card  
                // shows
                CardLayout cardLayout = (CardLayout) main_panel.getLayout();
                cardLayout.show(main_panel, "Add Item");
           }
        });

        // Add the addItemButton to the home page
        homeCard.add(addItemButton, BorderLayout.CENTER);
    }

    // the purpose of this method is to add all contents to addItemCard
    public static void formatAddItemCard(JPanel addItemCard)
    {
        // add 2 jtextfields, one for the budget title and the other for the budget amount
        // I excluded irrelevant JLabels, etc. for the sake of avoiding unnecessary details
        textfieldPanel.add(budget_Title_Field);
        textfieldPanel.add(amount_Field);
        addItemCard.add(textfieldPanel, BorderLayout.NORTH);

       // add functionality to save budget item button and add it to addItemCard
       saveBudgetItemButton.addActionListener(new ActionListener()
       {
             public void actionPerformed(ActionEvent e)
             {
                // If the data fields are complete, create and serialize the budget item. Else,
                // prompt the user for more information.   
                if (!(budget_Title_Field.getText().equals("")) && !(amount_Field.getText().equals("")))
                 {
                     // will save the budget data here. confirm the user saved the budget item.
                     JOptionPane.showMessageDialog(null, "Success! Your budget item was saved and has been integrated into your budget.");
                 }

                 // if either budget item title or amount is missing, complain and don't save budget item
                if (budget_Title_Field.getText().equals("") || amount_Field.getText().equals(""))
                {
                    // PROBLEMATIC CODE HERE: INCORRECTLY ASSUMES TEXTFIELDS ARE EMPTY WHEN THEY'RE 
                    // NOT AFTER CLICKING ON "PREVIOUS" BUTTON, THEN RETURNING TO THIS PAGE BY 
                    // CLICKING "ADD REVENUE OR EXPENSE" BUTTON
                    // print out error message that budget item title and amount is incomplete
                    JOptionPane.showMessageDialog(null, "Please enter in both the budget item title and dollar amount to continue.");
                }
            }
       });

       addItemCard.add(saveBudgetItemButton, BorderLayout.CENTER);

       // Add functionality to previous button and add it to the addItemCard
       previous.addActionListener(new ActionListener()
       {
            public void actionPerformed(ActionEvent e)
            {   
                // If the previous button is pressed, switch the JPanel so that the home page card shows
                CardLayout cardLayout = (CardLayout) main_panel.getLayout();
                cardLayout.show(main_panel, "Home");

                budget_Title_Field.setText("");
                amount_Field.setText("");
                isExpenseButton.setSelected(true); 
            }
        });

        addItemCard.add(previous, BorderLayout.SOUTH);
    }
}
  • If I make the modifications to make the sample program run, it works as expected. Do you possibly create new text fields in your real code somewhere, so that wrong fields get checked? I initialized them at the top of the class and nowhere else. – kiheru Dec 16 '14 at 07:36

0 Answers0