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 :-)

Recommended Answers

All 4 Replies

Please post your code, it will make it easier to find the problem.

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);
    }

}
Member Avatar for ztini

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());"

Thank you very much ztini :-) saved a lot of time searching for a solution

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.