Lazio
Lazio

Reputation: 105

GridLayout gives me an error after inserting panel into one of the grids

I have tried to create a GridLayout panel which consits of 5 rows and 1 column. I have created a temporary panel p and after adding components to it at the spot (1,1) it shows an error. Could you point out what's wrong with it because I'm staring at it for like over an hour trying to figure out what's wrong. The error says "The method GridLayout(int, int) is undefined for the type assignmentGUI". assignmentGUI is the name of my class. As soon as I create a method GridLayout using the template it works but doesn't seem to work properly.

This is the code I wrote:

import java.awt.*; import java.awt.event.*; import java.util.ArrayList; import java.util.Vector;

import javax.swing.*; import javax.swing.event.*; import javax.swing.border.*;

public class assignmentGUI extends JFrame {

    public assignmentGUI() {
                this.setTitle("Module Chooser Tool");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        this.setLayout(new FlowLayout(FlowLayout.LEFT));       
        //this.setPreferredSize(new Dimension(800, 500));


        JPanel p;

        // ***************************** PROFILE PANEL ************************************** //
        JPanel profilePanel = new JPanel();
        profilePanel.setLayout(new GridLayout(5,1));

        //--------Select course line---------------
        //Label
        JLabel courseLbl = new JLabel("Select course:");

        //ComboBox
        String[] choices = {"Computer Science", "Software Engineering"};
        JComboBox<String> combo = new JComboBox<String>(choices);

        //ADD everything
        p = new JPanel();
        p.add(courseLbl);
        p.add(combo);
        profilePanel.add(p, GridLayout(1,1));

...

Upvotes: 0

Views: 770

Answers (1)

camickr
camickr

Reputation: 324157

profilePanel.add(p, GridLayout(1,1));

First of all Java uses 0 offsets so the first row and first column would be represented by (0, 0), but that won't solve the problem.

When adding components the components are added to a panel sequentially. The layout manager will then layout the components based on the rules of the layout manager.

When you say new GridLayout(5, 1) this does not create 5 "place holders".

To add components to the panel you need to do:

panel.add(someComponent); // goes to row 0, column 0);
panel.add(anotherComponent); // goes to  row 1, column 0

Read the section from the Swing tutorial on Layout Managers for working examples to get you started with the basics.

Upvotes: 1

Related Questions