Problem switching graphics using CardLayout

1

Hello, I'm having trouble using CardLayout to display the graphs of two classes. I intended to show each graph at a time and display the other at the push of a button, however when I press the button the first graph continues to be drawn and the second appears overwriting the first one, causing the two graphs to appear at the same time. / p>

Main class

public class MainFrame extends JFrame{
    JPanel mainCard;
    JButton jb1, jb2;
    CardLayout cards;
    NRZL card1 = new NRZL();
    NRZI card2 = new NRZI();

    public MainFrame(){
        setSize(900,900);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setResizable(false);
        setTitle("Tela de escolha");

        jb1 = new JButton("Vá para NRZI");
        jb2 = new JButton("Vá para NRZL");

        jb1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                cards = (CardLayout) mainCard.getLayout();  
                cards.show(mainCard, "card 2");
            }
        });

        jb2.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                cards = (CardLayout) mainCard.getLayout();
                cards.show(mainCard, "card 1");
            }
        });

        card1.add(jb1);
        card2.add(jb2);

        mainCard = new JPanel(new CardLayout());
        mainCard.add(card1, "card 1");
        mainCard.add(card2, "card 2");

        getContentPane().add(mainCard);
        setVisible(true);
    }

    public static void main(String[] args){
        MainFrame mainFrame = new MainFrame();
    }
}

Chart class 1

public class NRZL extends JPanel{

    @Override
    public void paintComponent(Graphics g){
        super.repaint();
        g.drawOval(200, 200, 200, 200);        
    } 
}

Graph class 2

public class NRZI extends JPanel{

    @Override
    public void paintComponent(Graphics g){
        super.repaint();
        g.drawRect(300, 200, 200, 200);
    }

}

Thanks in advance for any help.

    
asked by anonymous 16.03.2017 / 19:55

1 answer

0

You can put a repaint

jb1.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
          repaint();
          cards = (CardLayout) mainCard.getLayout();  
          cards.show(mainCard, "card 2");


      }
  });

  jb2.addActionListener(new ActionListener() {
      @Override
      public void actionPerformed(ActionEvent e) {
        repaint();
        cards = (CardLayout) mainCard.getLayout();
        cards.show(mainCard, "card 1");

      }
  });
    
16.03.2017 / 20:54