Forum Stats

  • 3,854,261 Users
  • 2,264,344 Discussions
  • 7,905,624 Comments

Discussions

Error encountered while working with Swing components

Hi ,

I am totally new to java and exploring the Swing class concepts with the help of the below program.Basically add a panel to a frame.

package uicontrols;

import java.awt.*;

import javax.swing.*;

//import javax.swing.JPanel;

public class JPanel extends JFrame

{

JPanel obj2;

JFrame obj1;

public initialize()

{

    obj1 = new JFrame();

    setTitle("FrameDemo");

        setVisible(true);

setSize(300, 300);

        obj2 = new JPanel();

        obj2.setTitle("PanelDemo");

    obj2.setVisible(true);

obj2.setSize(300, 100);               

        obj1.add(obj2);

          

}

public static void main(String[] args) {

        JPanel jp = new JPanel();

              jp.initialize();

     

      

    }}

The program runs and show me a Frame Window and on top of it a Panel but gives the below errors as well.Can some pleas help me understand the cause of these errors.

Thanks in advance.

Exception in thread "main" java.lang.IllegalArgumentException: adding a window to a container

at java.awt.Container.checkNotAWindow(Container.java:490)

at java.awt.Container.addImpl(Container.java:1091)

at java.awt.Container.add(Container.java:1005)

at javax.swing.JFrame.addImpl(JFrame.java:567)

at java.awt.Container.add(Container.java:417)

at uicontrols.JPanel.initialize(JPanel.java:24)

at uicontrols.JPanel.main(JPanel.java:30)

Answers

  • Mridula03
    Mridula03 Member Posts: 2
    edited Feb 12, 2018 12:46AM

    Your code is not visible. Moreover you have not specified your requirements clearly. Still if this can help you, here it is....

    1) Set the layout of the content pane to null by calling getContentPane.setLayout(null);

    2) Add the panel to the content pane.

    3) Define the bounds of the panel by calling panel.setBounds(int x, int y, int width, int height) where x,y are the location and the width and height are the dimensions of the panel.

This discussion has been closed.