2016-11-27 46 views
-1

所以基本上我正在写一个GUI程序,使用JComboBox来显示各种财务公式。就显示公式而言,我已经掌握了一切,但这是我的问题。每次我去我的组合框中选择一个新的公式,其他的都保持显示。我试图写一个if语句来禁用,删除和使这些(一次不是全部)失效,但没有任何工作......我需要得到它,所以当我点击一个选项,其他面板消失,如果有任何。谢谢!删除Java面板而不会崩溃你的程序

以下是完整的程序我遇到的问题是,当我选择一个新的公式时,我选择了之前它仍然活动...我想禁用或删除它。谢谢。

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

} 
+1

你如果块失败,因为你比较字符串错误。你不应该用'=='或'!='来比较字符串。改为使用“equals(...)”或“equalsIgnoreCase(...)”方法。理解'=='检查两个*对象引用*是否相同,而不是你感兴趣的。另一方面,方法检查两个字符串是否具有相同顺序的相同字符,这就是这里很重要。 –

+1

在另一个说明中,您应该使用[CardLayout](http://docs.oracle.com/javase/tutorial/uiswing/layout/card.html) –

+0

交换组件?有没有人可以简单地在点击时将其删除一个新的? –

回答

1

再次,使用CardLayout来帮助您交换您的JPanel。您将创建一个JPanel并将其布局设置为CardLayout,然后您将使用字符串常量将要交换到此持有者JPanel的JPanel(“卡”)添加到您要传递到CardLayout的show(...)方法的字符串中允许它交换你的组件。

例如,假设你有一个枚举握住你的财务公式字符串,是这样的:

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

然后CardLayout和它的JPanel可以设立像这样:

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

和JComboBox如下所示。这工作,因为我已经覆盖了枚举对字符串的方法,使一个合适的名字会显示:

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

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

你会使用从枚举得到的字符串常量,然后添加的所有公式JPanels到cardHolderPanel

然后,当你想要交换JPanels,只需通过在适当的串入CardLayout的表演方法,你是好:

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

的FO llowing程序不会创建任何花哨的公式JPanels,但它并没有,因为它是一个内置MCVE证明只交换JPanels:

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