线程“main”中的异常将窗口添加到容器中

时间:2015-04-09 18:51:20

标签: java swing exception

我正在编写一个应用程序来点击jbutton来选择随机数。但是当我运行应用程序时,我得到了这个例外:

  

线程中的异常" main" java.lang.IllegalArgumentException:向容器添加窗口       在java.awt.Container.checkNotAWindow(Container.java:483)       在java.awt.Container.addImpl(Container.java:1084)       在java.awt.Container.add(Container.java:410)       在Final.main(Final.java:37)

这是我的代码:

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);        
    } 
}

1 个答案:

答案 0 :(得分:2)

而不是:

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

尝试类似:

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