0

I learned recently how to switch between Jpanels in CardLayout. The code works fine but when I attempt to change one of jPanels to Plot2DPanel I get a strange behaviour at runtime. The Plot2DPanel isn't picking up its mouse click events. What have I done wrong? (I assume that is not a bug in jmathplot).

Here's the code:

public class Window {

    private JFrame frame;
    private JPanel cards;
    private JPanel panelOne;
    private Plot2DPanel panelTwo;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Window window = new Window();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public Window() {
        initialize();
    }

    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100, 100, 790, 483);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        cards = new JPanel();
        cards.setLayout(new CardLayout());

        panelOne = new JPanel();
        panelOne.setBackground(Color.BLACK);
        panelOne.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e){
                java.awt.Toolkit.getDefaultToolkit().beep(); //debug beep
                CardLayout cl = (CardLayout) cards.getLayout();
                cl.next(cards);
            }
        });

        panelTwo = new Plot2DPanel();
        panelTwo.setBackground(Color.WHITE);
        panelTwo.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e){
                java.awt.Toolkit.getDefaultToolkit().beep(); //debug beep
                CardLayout cl = (CardLayout) cards.getLayout();
                cl.next(cards);
            }
        });

        cards.add(panelOne, "panel1");
        cards.add(panelTwo, "panel2");

        frame.getContentPane().add(cards);
    }

}
Community
  • 1
  • 1
Vlad K.
  • 320
  • 3
  • 19
  • `I assume that is not a bug in jmathplot` - 1) Did you try to replace that panel with a regular JPanel? 2) if you move the mouse even 1 pixel between the mousePressed and mouseReleased events a mouseClicked event will not be generated. Try using a mousePressed event. – camickr May 07 '16 at 22:06
  • @camickr 1) yes regular panel works fine 2) doesn't work. – Vlad K. May 08 '16 at 05:09

0 Answers0