2
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
>>>import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import javax.swing.JButton;
import javax.swing.BorderFactory;
public class GridBagLayout {
    public static void createWindow(){
        JFrame aWin = new JFrame("Title");
        aWin.setBounds(0,0,200,200);
        aWin.setVisible(true);

        GridBagLayout gridBag = new GridBagLayout();
        GridBagConstraints constraints = new GridBagConstraints();
        >>>aWin.getContentPane().setLayout(gridBag);


        constraints.weightx = constraints.weighty = 10.0;
        constraints.fill = GridBagConstraints.BOTH;
        addButton(" Press ",constraints,gridBag,aWin);
        constraints.gridwidth=GridBagConstraints.REMAINDER;
    }
    static void addButton(String label,GridBagConstraints constraints,GridBagLayout layout,JFrame window){
        JButton button = new JButton(label);
        button.setBorder(BorderFactory.createEtchedBorder());
        >>>layout.setConstraints(button,constraints);
        window.getContentPane().add(button);
    }
    public static void main(String[] args){
        SwingUtilities.invokeLater(new Runnable(){
            public void run(){
                createWindow();
            }
        });
    }
}

The lines marked with >>> are flagged as error by Eclipse IDE.
The error for import java.awt.GridBagLayout; states that there is a possible conflict with the type within the same file
The error for aWin.getContentPane().setLayout(gridBag); states that GridBagLayout can not be applied although when I tried FlowLayout, it was fine.
The error for layout.setConstraints(button,constraints); states that the method is undefined.
What is the cause for this error? Please help me solve it.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Dummy Derp
  • 237
  • 1
  • 3
  • 15

2 Answers2

2

These are caused by the fact that you named your class GridBagLayout. You need to either change the name of your class or use explicit full path for all uses of the java.awt.GridBagLayout class and not use an import for it.

Don Roby
  • 40,677
  • 6
  • 91
  • 113
2

The compile error pretty much describes the problem. Simply rename your class to, say, GridBagLayoutTest.

Reimeus
  • 158,255
  • 15
  • 216
  • 276