-1

So basically I am writing a GUI program that uses a JComboBox to display various finance formulas. I have everything in place in terms of it displaying the formulas but here is my problem. Everytime I go to choose a new formula in my comboBox it the other ones stay displayed. I've tried to write an if statement to disable, remove and invalidate these (not all at once) but none have worked...I need to get it so when I click a option the other panels disappear if there are any at all. Thanks!

Here is the full program the problem I am having is that when I choose a new formula the one that I chose before it is still active...I want to disable or remove it. Thanks.

import java.awt.BorderLayout;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.text.DecimalFormat;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;





public class newFinanceFullClass extends JFrame {


           private JMenu fileMenu;
           private JMenuItem exitItem;

           private JPanel presentValuePanel;  
           private JPanel financeFinderPanel;// A panel container
           private JLabel principalMessage;  
           private JLabel yearlyRateMessage;
           private JLabel termYearMessage;
           private JPanel simpleInterestPanel;
           private JPanel doublingTimePanel;
           private JPanel compoundInterestPanel;
           private JLabel NONEMessage;
           private JLabel imageLabel;
           private JLabel label;// A message to display
           private JMenuBar menuBar;
           private JTextField principalText; // To hold user input
           private JButton calcButton;       // Performs calculation
           private final int WINDOW_WIDTH = 600;  // Window width
           private final int WINDOW_HEIGHT = 600; // Window height
           private JTextField yearlyRateText;
           private JTextField termYearText;
           DecimalFormat dc =new DecimalFormat("####0.00"); //formater 
           private JComboBox financeBox; 
           double principal = 400.0;
           double yearlyRate = .04;
           double termYears = 4.0;

           private String[] financeFormulas = { "NONE", "Present value", "Simple interest",
                   "Doubling time", "Compound interest", "Decaf"};


           financeFormulaClass financeFormula = new financeFormulaClass(principal, yearlyRate, termYears);

           /**
            *  Constructor
            */

           public newFinanceFullClass()
           {
              // Call the JFrame constructor.
              super("Finance Class");

              // Set the size of the window.
              setSize(WINDOW_WIDTH, WINDOW_HEIGHT);

              // Specify what happens when the close
              // button is clicked.
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

              // Build the panel and add it to the frame.
              financeFinderPanel();
              setLayout(new BorderLayout());

              //buildPanel();

              menuBar = new JMenuBar();
              buildFileMenu();
              menuBar.add(fileMenu);
              setJMenuBar(menuBar);

              // Add the panel to the frame's content pane.
              add(financeFinderPanel);
              //add(panel);

              // Display the window.
              setVisible(true);
           }

           private void financeFinderPanel()
           {
              // Create a panel to hold the combo box.


              financeFinderPanel = new JPanel();

              //create label
              label = new JLabel("Pick your formula");
              ImageIcon funnyImage = new ImageIcon("funny.gif");
              imageLabel = new JLabel();
              imageLabel.setLocation(50, 55);

              label.setForeground(Color.BLUE);
              // Create the combo box
              financeBox = new JComboBox(financeFormulas);
              imageLabel.setIcon(funnyImage);
              // Register an action listener.
              financeBox.addActionListener(new financeBoxListener());
              exitItem = new JMenuItem("Exit");   
              exitItem.setMnemonic(KeyEvent.VK_X);

              // Add the combo box to the panel.
              financeFinderPanel.add(financeBox);
              financeFinderPanel.add(label);
              financeFinderPanel.add(imageLabel);


           }

          /** private void menuList(){
            exitItem = new JMenuItem("Exit");   
            exitItem.setMnemonic(KeyEvent.VK_X);
            menuList.add(exitItem);
           } **/

           private void buildMenuBar()
           {
              // Create the menu bar.
              menuBar = new JMenuBar();

              // Create the file and text menus.
              buildFileMenu();
             // buildTextMenu();

              // Add the file and text menus to the menu bar.
              menuBar.add(fileMenu);
              //menuBar.add(textMenu);

              // Set the window's menu bar.
              setJMenuBar(menuBar);
           }





               private void buildFileMenu()
               {
                  // Create an Exit menu item.
                  exitItem = new JMenuItem("Exit");
                  exitItem.setMnemonic(KeyEvent.VK_X);
                  exitItem.addActionListener(new ExitListener());


                  // Create a JMenu object for the File menu.
                  fileMenu = new JMenu("File");
                  fileMenu.setMnemonic(KeyEvent.VK_F);

                  // Add the Exit menu item to the File menu.
                  fileMenu.add(exitItem);

               }





           private void presentValuePanel()
           {
              // Create the label, text field, and button components.
              principalMessage = new JLabel("principal");
              principalText = new JTextField(10);
              yearlyRateMessage = new JLabel("Yearly Rate");
              yearlyRateText = new JTextField(10);
              termYearMessage = new JLabel("Term Year");
              termYearText = new JTextField(10);
              calcButton = new JButton("Calc Present Value");

              // Add an action listener to the button.
              //calcButton.addActionListener(new CalcButtonListener());

              calcButton.addActionListener(new financeFormListener());

              // Create a panel to hold the components.
              presentValuePanel = new JPanel();

              // Add the label, text field, and button to the panel.
              presentValuePanel.add(principalMessage);
              presentValuePanel.add(principalText);
              presentValuePanel.add(yearlyRateMessage);
              presentValuePanel.add(yearlyRateText);
              presentValuePanel.add(termYearMessage);
              presentValuePanel.add(termYearText);
              presentValuePanel.add(calcButton);
           }


          private void simpleInterestPanel(){

               principalMessage = new JLabel("principal");
                  principalText = new JTextField(10);
                  yearlyRateMessage = new JLabel("Yearly Rate");
                  yearlyRateText = new JTextField(10);
                  termYearMessage = new JLabel("Term Year");
                  termYearText = new JTextField(10);
                  calcButton = new JButton("Calc Simple Interest");

                  simpleInterestPanel = new JPanel();
                  calcButton.addActionListener(new financeFormListener());

                  simpleInterestPanel.add(principalMessage);
                  simpleInterestPanel.add(principalText);
                  simpleInterestPanel.add(yearlyRateMessage);
                  simpleInterestPanel.add(yearlyRateText);
                  simpleInterestPanel.add(termYearMessage);
                  simpleInterestPanel.add(termYearText);
                  simpleInterestPanel.add(calcButton);



           }

          private void doublingTimePanel(){


              yearlyRateMessage = new JLabel("Yearly Rate");
              yearlyRateText = new JTextField(10);

              calcButton = new JButton("Calc Doubling Time");
              calcButton.addActionListener(new financeFormListener());


              doublingTimePanel = new JPanel();

              doublingTimePanel.add(yearlyRateMessage);
              doublingTimePanel.add(yearlyRateText);
              doublingTimePanel.add(calcButton);

          }

          private void compoundInterestPanel(){


              principalMessage = new JLabel("principal");
              principalText = new JTextField(10);
              yearlyRateMessage = new JLabel("Yearly Rate");
              yearlyRateText = new JTextField(10);
              termYearMessage = new JLabel("Term Year");
              termYearText = new JTextField(10);
              calcButton = new JButton("Calc Compound Interest");

              compoundInterestPanel = new JPanel();
              calcButton.addActionListener(new financeFormListener());

              compoundInterestPanel.add(principalMessage);
              compoundInterestPanel.add(principalText);
              compoundInterestPanel.add(yearlyRateMessage);
              compoundInterestPanel.add(yearlyRateText);
              compoundInterestPanel.add(termYearMessage);
              compoundInterestPanel.add(termYearText);
              compoundInterestPanel.add(calcButton);

          }


           //Listener to choose which formula

           private class financeBoxListener implements ActionListener
           {
              public void actionPerformed(ActionEvent e)
              {

                  Object actionCommand = e.getSource();
                  String selection = (String) financeBox.getSelectedItem();
                  if(selection.equals("Present value")){
                      //financeFinderPanel.removeAll();




                      presentValuePanel();
                      add(presentValuePanel, BorderLayout.SOUTH);

                      pack();


                  }



                 else if(selection.equals("Simple interest")){



                     simpleInterestPanel();
                     add(simpleInterestPanel, BorderLayout.NORTH);


                     pack();

                  }
                 else if(selection.equals("Doubling time")){
                     doublingTimePanel();
                     add(doublingTimePanel, BorderLayout.SOUTH);
                     pack();

                 }
                 else if(selection.equals("Compound interest")){

                    compoundInterestPanel();
                    add(compoundInterestPanel, BorderLayout.NORTH);
                    pack();

                 }
                 else if(selection.equals("NONE")){

                      setSize(200, 150);
                      financeFinderPanel();
                      add(financeFinderPanel, BorderLayout.NORTH);
                      NONEMessage = new JLabel("PICK A SELECTION");


                  }





              }
           }



           private class financeFormListener implements ActionListener{

            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub


                String actionCommand = e.getActionCommand();
                if(actionCommand.equals("Calc Simple Interest")){


                        try{
                        double principal = Double.parseDouble(principalText.getText());
                        double yearlyRate = Double.parseDouble(yearlyRateText.getText());
                        double termYears = Double.parseDouble(termYearText.getText());
                        double interestRate = (principal * yearlyRate * termYears);

                        String msg = "Simple interest is: $" + dc.format(interestRate);
                        JOptionPane.showMessageDialog(null, msg);
                        }
                        catch(NumberFormatException r){

                            JOptionPane.showMessageDialog(null, "Please insert formula information");

                        }

                }
                else if(actionCommand.equals("Calc Present Value"))


                {

                    try{
                double principal = Double.parseDouble(principalText.getText());
                double yearlyRate = Double.parseDouble(yearlyRateText.getText());
                double termYears = Double.parseDouble(termYearText.getText());

                double pValue = financeFormula.presentValue(principal, yearlyRate, termYears);
                //double pValue = principal * (((1- Math.pow(1 + yearlyRate, -termYears))/ yearlyRate));
                String msg = "Present value is: $" + dc.format(pValue);


                JOptionPane.showMessageDialog(null, msg);
                    }
                 catch(NumberFormatException r){

                     JOptionPane.showMessageDialog(null, "Please insert formula information");
                 }
                }

                else if(actionCommand.equals("Calc Doubling Time")){



                    try{
                    double yearlyRate = Double.parseDouble(yearlyRateText.getText());
                    double dValue = financeFormula.doublingTime(yearlyRate);
                    String msg = "Doubling Time is: " + dc.format(dValue);
                    JOptionPane.showMessageDialog(null, msg);
                    }
                    catch(NumberFormatException r){

                        JOptionPane.showMessageDialog(null, "Please insert formula information");
                    }
                }

                else if(actionCommand.equals("Calc Compound Interest")){

                    try{
                        double principal = Double.parseDouble(principalText.getText());
                        double yearlyRate = Double.parseDouble(yearlyRateText.getText());
                        double termYears = Double.parseDouble(termYearText.getText());
                        double compoundInterest = financeFormula.compoundInterest(principal, yearlyRate, termYears);
                        String msg = "Compound Interest is: $" + dc.format(compoundInterest);
                        JOptionPane.showMessageDialog(null, msg);
                    }
                    catch(NumberFormatException r){

                        JOptionPane.showMessageDialog(null, "Please insert formula information");

                    }
                }
                }






            }

           private class ExitListener implements ActionListener
            {
              public void actionPerformed(ActionEvent e)
              {
                 System.exit(0);
              }
            }














           public static void main(String[] args)
           {
              new newFinanceFullClass();
           }

}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • 1
    Your if blocks fail because you're comparing Strings wrong. You shouldn't compare Strings using `==` or `!=`. Use the `equals(...)` or the `equalsIgnoreCase(...)` method instead. Understand that `==` checks if the two *object references* are the same which is not what you're interested in. The methods on the other hand check if the two Strings have the same characters in the same order, and that's what matters here. – Hovercraft Full Of Eels Nov 27 '16 at 16:21
  • 1
    On another note, you should swap components using a [CardLayout](http://docs.oracle.com/javase/tutorial/uiswing/layout/card.html) – Hovercraft Full Of Eels Nov 27 '16 at 16:22
  • Is there anyone to simply to remove them when I click on a new one? – Kody Evangelist Dibble Nov 27 '16 at 16:54
  • I'm sorry, I'm not sure what you mean. Do you mean remove a JPanel and display nothing in its place? If so, and you're using a CardLayout, swap in an empty JPanel or an empty JLabel. – Hovercraft Full Of Eels Nov 27 '16 at 17:22
  • So I want it so when I choose a new formula after I already have a formula displayed it will take the former formula off...I need to learn how to use the card layout if you think that is the only way. – Kody Evangelist Dibble Nov 27 '16 at 17:27
  • It's hard to answer as we have no idea how you're displaying "formulas" in your GUI. It could mean that your formula display component needs some sort of `public void reset() {...}` method where it clears itself, but again, I'm just guessing here. – Hovercraft Full Of Eels Nov 27 '16 at 17:29
  • Ok so I have a JPanel for each formula, and in my actionListener I call those individual panels every time I make a selection with my ComboBox. So the problem is when I choose one, then another they both appear. I only want one to appear. So I need to somehow disable or remove the others. I tried a removeall(); on the individual panels but it only works when I have it in that order otherwise it throws an error hope this clears it up thanks again. – Kody Evangelist Dibble Nov 27 '16 at 17:36
  • 1
    The best way to get us to fully and quickly understand your problem would be if you were to to create and post a [minimal example program](http://stackoverflow.com/help/mcve), a small (able to post the complete program in your question as code-formatted text) but complete (compilable and runnable) program that only has necessary code to demonstrate your problem, that we can copy, paste, compile and run without modification. – Hovercraft Full Of Eels Nov 27 '16 at 17:40
  • Should I display this in the comment section or make another? – Kody Evangelist Dibble Nov 27 '16 at 17:46
  • Never display code like this in comments. We're talking about a real program, perhaps 100 lines or less. It should either be in a new question or as an edit to this question. Also explain what the code does, what it doesn't do, and what problems you're having. – Hovercraft Full Of Eels Nov 27 '16 at 17:47
  • Problems: 1) it's not a valid [mcve] -- It's too large and contains much that is not relevant to your problem and does not compile for me due to unnecessary outside class dependencies. Please re-read the MCVE link. 2) You've not followed my CardLayout recommendation which now **is** the solution to your problem. – Hovercraft Full Of Eels Nov 27 '16 at 19:14
  • Please see edits to answer and let know if anything is confusing. – Hovercraft Full Of Eels Nov 28 '16 at 17:00

1 Answers1

1

Again, use a CardLayout to help you swap your JPanels. You would create a JPanel and set its layout to CardLayout, and then you'd add the JPanels (the "cards") that you wish to swap into this holder JPanel using String constants, Strings that you will pass into the CardLayout's show(...) method to allow it to swap your components.

For instance, say you had an enum to hold your financial formula Strings, something like:

public enum FinanceFormula {
    NONE("NONE"), 
    PRESENT_VALUE("Present value"), 
    SIMPLE_INTEREST("Simple interest"),
    DOUBLING_TIME("Doubling time"), 
    COMPOUND_INTEREST("Compound interest"), 
    DECAF("Decaf");

    private String name;

    private FinanceFormula(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return getName();
    };
}

Then the CardLayout and its JPanel could be set up like so:

private CardLayout cardLayout = new CardLayout();
private JPanel cardHolderPanel = new JPanel(cardLayout);

and the JComboBox like below. This works because I have overridden the enum's to String method so that a proper name will display:

private JComboBox<FinanceFormula> comboBox = new JComboBox<>(FinanceFormula.values());

You would then add all the formula JPanels into the cardHolderPanel using String constants obtained from the enum:

// fill the cardHolderPanel with "cards", JPanels with formula:
cardHolderPanel.add(createNonePanel(), FinanceFormula.NONE.getName());
cardHolderPanel.add(createPresentValuePanel(), FinanceFormula.PRESENT_VALUE.getName());
cardHolderPanel.add(createSimpleInterestPanel(), FinanceFormula.SIMPLE_INTEREST.getName());
cardHolderPanel.add(createDoublingTimePanel(), FinanceFormula.DOUBLING_TIME.getName());
cardHolderPanel.add(createCompoundInterestPanel(), FinanceFormula.COMPOUND_INTEREST.getName());
cardHolderPanel.add(createDecafPanel(), FinanceFormula.DECAF.getName());

Then when you want to swap JPanels, simply pass in the appropriate String into the CardLayout's show method, and you're good:

private void combBoxActionPerformed(ActionEvent e) {
    FinanceFormula selectedFormula = (FinanceFormula) comboBox.getSelectedItem();
    cardLayout.show(cardHolderPanel, selectedFormula.getName());
}

The following program doesn't create any fancy formula JPanels, but it doesn't have to, since it is an MCVE built to demonstrate swapping JPanels only:

import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;

import javax.swing.*;

@SuppressWarnings("serial")
public class NewFinance2 extends JPanel {
    private CardLayout cardLayout = new CardLayout();
    private JPanel cardHolderPanel = new JPanel(cardLayout);
    private JComboBox<FinanceFormula> comboBox = new JComboBox<>(FinanceFormula.values());

    public NewFinance2() {
        // fill the cardHolderPanel with "cards", JPanels with formula:
        cardHolderPanel.add(createNonePanel(), FinanceFormula.NONE.getName());
        cardHolderPanel.add(createPresentValuePanel(), FinanceFormula.PRESENT_VALUE.getName());
        cardHolderPanel.add(createSimpleInterestPanel(), FinanceFormula.SIMPLE_INTEREST.getName());
        cardHolderPanel.add(createDoublingTimePanel(), FinanceFormula.DOUBLING_TIME.getName());
        cardHolderPanel.add(createCompoundInterestPanel(), FinanceFormula.COMPOUND_INTEREST.getName());
        cardHolderPanel.add(createDecafPanel(), FinanceFormula.DECAF.getName());

        comboBox.addActionListener(e -> combBoxActionPerformed(e));
        JPanel northPanel = new JPanel();
        northPanel.add(comboBox);

        setLayout(new BorderLayout());
        add(cardHolderPanel, BorderLayout.CENTER);
        add(northPanel, BorderLayout.NORTH);
    }

    private void combBoxActionPerformed(ActionEvent e) {
        FinanceFormula selectedFormula = (FinanceFormula) comboBox.getSelectedItem();
        cardLayout.show(cardHolderPanel, selectedFormula.getName());
    }


    // A bunch of dummy methods that don't create much
    // Your real methods would create more complex JPanels
    private JPanel createDecafPanel() {
        return createPanel(FinanceFormula.DECAF);
    }

    private JPanel createCompoundInterestPanel() {
        return createPanel(FinanceFormula.COMPOUND_INTEREST);
    }

    private JPanel createDoublingTimePanel() {
        return createPanel(FinanceFormula.DOUBLING_TIME);
    }

    private JPanel createSimpleInterestPanel() {
        return createPanel(FinanceFormula.SIMPLE_INTEREST);
    }

    private JPanel createPresentValuePanel() {
        return createPanel(FinanceFormula.PRESENT_VALUE);
    }

    private JPanel createNonePanel() {
        return createPanel(FinanceFormula.NONE);
    }   

    // temporary method just for demonstration purposes
    private JPanel createPanel(FinanceFormula financeFormula) {
        JLabel label = new JLabel(financeFormula.getName());
        label.setFont(label.getFont().deriveFont(Font.BOLD, 24f));

        JPanel panel = new JPanel(new GridBagLayout());
        panel.add(label);
        panel.setPreferredSize(new Dimension(400, 300));
        float split = 0.7f;
        float h = (float) (split + Math.random() * (1f - split));
        float s = (float) (split + Math.random() * (1f - split));
        float b = (float) (split + Math.random() * (1f - split));
        Color color = Color.getHSBColor(h, s, b);
        panel.setBackground(color);
        return panel;
    }

    private static void createAndShowGui() {
        NewFinance2 mainPanel = new NewFinance2();

        JFrame frame = new JFrame("Finance");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(mainPanel);
        frame.pack();
        frame.setLocationByPlatform(true);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> createAndShowGui());
    }
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373