0

I am trying to learn Java Swing from a very old tutorial. As I was following the course I got stuck in a project where I was learning about GridBagLayout. When I called the function setLayout(new GridBagLayout());, Eclipse shows me 'GridBagLayout cannot be resolved to a type'. Even though I have imported java. awt. GridBagLayout.

Here's my code.

package com.swing11;

import java.awt.Dimension;
import java.awt.GridBagLayout;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.Border;

public class FormPanel extends JPanel {

    private JLabel nameLabel;
    private JLabel occupationLabel;
    private JTextField nameField;
    private JTextField occupationField;
    private JButton okButton;

    public FormPanel() {

        nameLabel = new JLabel("Name: ");
        occupationLabel = new JLabel("Occupation: ");
        nameField = new JTextField(10);
        occupationField = new JTextField(25);
        okButton = new JButton("Ok");

        Dimension dim = getPreferredSize();

        dim.width = 250;
        setPreferredSize(dim);

        Border innerBorder = BorderFactory.createTitledBorder("Add Person");
        Border outterBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5);

        setBorder(BorderFactory.createCompoundBorder(outterBorder, innerBorder));

        setLayout(new GridBagLayout());
    }

}

kleopatra
  • 51,061
  • 28
  • 99
  • 211
Ahsan
  • 19
  • 4
  • There is even an example in the APIDOC of GridBagLayout. Not that applets play a role in today's world... https://docs.oracle.com/en/java/javase/19/docs/api/java.desktop/java/awt/GridBagLayout.html – Queeg Jan 13 '23 at 20:25
  • Maybe this helps: https://stackoverflow.com/questions/15794821/eclipse-error-cannot-be-resolved-to-a-type. – tniessen Jan 13 '23 at 20:26
  • 1
    You haven't added your Swing components to the `JPanel`. Oracle has a helpful tutorial, [Creating a GUI With Swing](https://docs.oracle.com/javase/tutorial/uiswing/index.html). Skip the Learning Swing with the NetBeans IDE section. Pay particular attention to the [How to Use GridBagLayout](https://docs.oracle.com/javase/tutorial/uiswing/layout/gridbag.html) section. – Gilbert Le Blanc Jan 13 '23 at 21:02
  • Seems like I had an issue with Eclipse. It working fine now. Thank you. – Ahsan Jan 14 '23 at 07:21

0 Answers0