Get error in Swing java - IllegalArgumentException

632 views Asked by At

Tried to put on frame some swing components. This code worked to days ago. Now it's not work, didn't nothing. Maybe somebody can tell me what it's wrong?

public static void main(String[] args) {
    JFrame mainFrame = new JFrame();
    mainFrame.setSize(500, 400); //Size of frame
    mainFrame.setTitle("Cinema City"); //Set title
    mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 

    JLabel mainLabel = new JLabel("Welcome to Cinema City catalog!");
    JLabel actorLabel = new JLabel("Actors: ");
    JLabel laLabel = new JLabel("Last added: ");
    JLabel searchLabel = new JLabel("How to search ?");

    GridBagConstraints gbc = new GridBagConstraints();

    mainFrame.add(mainLabel, new GridBagConstraints(4, 0, 1, 3, 1, 1,
            GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL,
            new Insets(20, 160, 0, 0), 0, 0));

    mainFrame.add(actorLabel, new GridBagConstraints(0, 0, 1, 1, 1, 1,
            GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL,
            new Insets(100, 0, 0, 0), 0, 0));

    mainFrame.setVisible(true);

This is the error:

Exception in thread "main" java.lang.IllegalArgumentException: cannot add to layout: constraint must be a string (or null)
at java.awt.BorderLayout.addLayoutComponent(Unknown Source)
at javax.swing.JRootPane$1.addLayoutComponent(Unknown Source)
at java.awt.Container.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at javax.swing.JFrame.addImpl(Unknown Source)
at java.awt.Container.add(Unknown Source)
at GUI.main(GUI.java:40)
3

There are 3 answers

0
SASIKUMAR SENTHILNATHAN On BEST ANSWER

Layout is not mentioned for the particular JFrame - mainframe

Add this line after the JFrame declaration

mainFrame.setLayout(new GridBagLayout());

Should work fine.

0
Dragondraikk On

You're not actually setting your layout to GridBagLayout, so it is still the default (which would be a FlowLayout).

Of course, only a GridBagLayout can actually handle GridBagConstraints. This can be fixed by changing your declaration to JFrame mainFrame = new JFrame(new GridBagLayout());

0
A.K. On

you are not set frame layout . after creation object of frame write this code.

 new GridBagLayout();
 mainFrame.setLayout(gbl);

its work