Search code examples
javaswingjpaneljfreechart

Next and Previous Buttons Displaying Charts Malfunction


I am trying to step through a ArrayList<JPanel> which contains ChartPanels. The Next button correctly steps through the charts as expected, but when I click the Previous button nothing happens. I feel like my logic may be convoluted. Thanks!

Note: panelCombination is a JPanel.

Code for the buttons:

public static int advance = 0;
public static ArrayList<JPanel> chartList = new ArrayList<>();

private void NextMouseClicked(java.awt.event.MouseEvent evt) {                                  

        panelCombination.removeAll();
        panelCombination.add(chartList.get(advance));
        panelCombination.validate();
        if (advance < chartList.size()-1) {
            advance++;
        }
}                                 

private void PreviousMouseClicked(java.awt.event.MouseEvent evt) {                                      

    if (advance > 0) {
         advance--;
    }
    panelCombination.removeAll();
    panelCombination.add(chartList.get(advance));
    panelCombination.validate();
}                            

Solution

  • Use a CardLayout to change views, instead of trying to remove and add panels. What you're trying to do can easily be accomplished by calling the next() and previous() methods of the CardLayout. All you really need to do is set the layout of your panelCombination to CardLayout, add all you panels to the panelCombination and use those methods

    CardLayout layout = new CardLayout();
    panelCombination.setLayout(layout);
    // add all panels.
    ....
    private void PreviousMouseClicked(java.awt.event.MouseEvent evt) { 
        layout.previous(panelCombination);
    

    See more at How to Use CardLayout

    Also from the looks of you method signatures, it looks like you are using NetBeans GUI Builder. You can see How to Use CardLayout with Netbeans GUI Builder