Hello Guys,

I'm trying to learn how to use the GridBagLayout manager... but when I write it like the following: JPanel panel = new JPanel(new GridBagLayout());, Java tells me the following: cannot find symbol
symbol: constructor JPanel(gridbaglayout.GridBagLayout)
location: class.javax.swing.JPanel.

When this didn't work, I tried type casting JPanel panel = new JPanel((LayoutManager) new GridBagLayout());, this give me an error when I compile the code :Exception in thread "main" java.lang.ClassCastException: gridbaglayout.GridBagLayout cannot be cast to java.awt.LayoutManager
at gridbaglayout.GridBagLayout.main(GridBagLayout.java:21)

What am I doing wrong?, I looked at http://download.oracle.com/javase/tutorial/uiswing/layout/gridbag.html and this is how they show it but it doesn't work for me.


Any help is appreciated :-)

Here you go:

package gridbaglayout;
import javax.swing.*;
import java.awt.*;
/**
 *
 * @author Taimoor
 */
public class GridBagLayout {


    public static void main(String[] args) {
        JFrame frame = new JFrame("GridBagLayout");
        frame.setSize(500,500);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JPanel panel = new JPanel((LayoutManager) new GridBagLayout());
        frame.add(panel);
        GridBagConstraints c = new GridBagConstraints();
        JLabel label1 = new JLabel("test 1");
        c.gridx = 0;
        c.gridy = 0;
        panel.add(label1,c);
        JLabel label2 = new JLabel("test 2");
        c.gridx = 1;
        c.gridy = 0;
        panel.add(label2,c);
        JLabel label3 = new JLabel("test 3");
        c.gridx = 2;
        c.gridy = 0;
        panel.add(label3,c);
        JLabel label4 = new JLabel("test 4");
        c.gridx = 3;
        c.gridy = 0;
        panel.add(label4,c);
    }

}

The reason is you overrode the GridBagLayout class when you named your class the same thing. So, when you do " JFrame frame = new JFrame("GridBagLayout");", you're trying to create a new JFrame with your class as the parameter, hence the exception. So just rename your class to something else.

You will also not need to cast the LayoutManager, so change your JPanel to: " JPanel panel = new JPanel(new GridBagLayout());"

This question has already been answered. Start a new discussion instead.