mcguirjk
mcguirjk

Reputation: 41

Exception in thread "main" adding window to container

I am writing an app to select random numbers with a click on the jbutton. But when i run the app i get this exception:

Exception in thread "main" java.lang.IllegalArgumentException: adding a window to a container at java.awt.Container.checkNotAWindow(Container.java:483) at java.awt.Container.addImpl(Container.java:1084) at java.awt.Container.add(Container.java:410) at Final.main(Final.java:37)

Here is my code:

import java.util.ArrayList;
import java.awt.*;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;


public class Final extends JPanel {

    public static void main(String[] args) {

        // Random numbers that i have selected
        ArrayList numbers = new ArrayList();
        numbers.add(40);
        numbers.add(500);
        numbers.add(90);
        numbers.add(10);
        numbers.add(50);
        numbers.add(25);

        // The panel for the GUI
        JPanel panel = new JPanel();
        // And of course the frame and its characteristics
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("Random Numbers!");
        frame.setVisible(true);
        frame.setSize(300,150);


        // The button for selecting a random number from the arraylist
        JButton button = new JButton();
        button.setText("Click me!");

        // Finally add the objects to the panel
        frame.add(button);
        panel.add(frame);        
    } 
}

Upvotes: 0

Views: 420

Answers (1)

Andrew Thompson
Andrew Thompson

Reputation: 168845

Instead of:

    // Finally add the objects to the panel
    frame.add(button);
    panel.add(frame);        

Try something like:

    // Finally add the objects to the panel
    frame.add(button, BorderLayout.PAGE_START); // top of the frame
    frame.add(panel); // defaults to CENTER

Upvotes: 2

Related Questions