java - 线程 "main"向容器添加窗口时出现异常

标签 java swing exception

我正在编写一个应用程序,通过单击 jbutton 来选择随机数。但是当我运行该应用程序时,我收到此异常:

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)

这是我的代码:

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

最佳答案

而不是:

    // 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

关于java - 线程 "main"向容器添加窗口时出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29546616/

相关文章:

java - 如何在Spring Boot应用程序中添加方法级别身份验证?

java带有数组和int的新构造函数

java - 如何从网络存储中检索音频

java - JTable 列跨越

c# - 带有 System.Object 对象的 XmlSerializer

c++ - SIGABRT 在异常类的析构函数中

c++ - 在派生类构造函数中抛出异常。为什么调用基类析构函数而不调用派生类析构函数?

java - 智能 : show decompiled class disassembly even when source is present

java - 将值从子面板传递到父面板

java - elasticsearch中的数组搜索