tags:

views:

31

answers:

3

Hi all,

This is the problem, I have a class MainWindow that extends JFrame in one of the setup routines I set the layout of the class to a new CardLayout(). This all works fine but when I go to request the the layout from the JFrame and cast what it returns to a CardLayout I get errors because it is returning a BorderLayout. I think you get the picture from hear.

Please find some code below:

public MainWindow()
{
    initWindow();
}

public void actionPerformed(ActionEvent e)
{
    CardLayout m = (CardLayout)super.getLayout();
    m.next(this);
}

private void initWindow()
{
    super.getContentPane().setLayout(_mainLayout);
    super.setTitle(_WINDOW_NAME);
    super.setSize(_DEFAULT_WINDOW_SIZE);
    super.setLocationRelativeTo(null);
    super.setAlwaysOnTop(true);
    super.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    super.setResizable(false);

    init_buttons_panel();
    super.add(_buttons_panel, "bpanel");
}

Any help is greatly appreciated.

Wow all of these questions but yet not one helpful one.

I see that the code is not perfect this is because I have been trying everything to trap the problem. Yes I realize casting like that is not good but this is just test code to prove the point. Oh and _mainLayout is you guessed it a CardLayout.

I have also read how to use card layout and my code does not do anything out of the ordinary.

Any more unhelpful answers?

+1  A: 

First, you should not cast a layout like that, at least without making any verifications. You should use the instanceof keyword first, to check if it really is a CardLayout, to prevent the program from finishing abruptly.

Second, the problem is here:

public void actionPerformed(ActionEvent e)
{
    CardLayout m = (CardLayout)super.getContentPane().getLayout();
    m.next(this);
}

Basicly you were getting the layout of the JFrame, and not from the JFrame's content pane, which is the one you actually set to be a CardLayout.

Luis Miguel
A: 

The getLayout method of JFrame is inherited from Container and thus does not forward on the call to the JFrame's content pane. You could try using super.getContentPane().getLayout() instead of super.getLayout().

jwaddell
+1  A: 
super.getContentPane().setLayout(_mainLayout); 

The code you posted doesn't help us since we don't have all the information. We don't know what the variable _mainLayout refers to.

I suggest you start by reading the section from the Swing tutorial How to Use Card Layout for a working example and a better designed program. For one thing there is no reason to extend JFrame since you haven't added any functionality.

camickr