简体   繁体   English

无法将任何组件添加到 JFrame - IllegalArgumentException

[英]Can't add any component to JFrame - IllegalArgumentException

When I try to add anything to JFrame in constructor and I have IllegalArgumentException.当我尝试在构造函数中向 JFrame 添加任何内容时,我遇到了 IllegalArgumentException。

Similar code is working in documentation: https://docs.oracle.com/javase/tutorial/uiswing/layout/none.html类似的代码正在文档中工作: https://docs.oracle.com/javase/tutorial/uiswing/layout/none.html

Why my very simple code doesn't work?为什么我非常简单的代码不起作用? It is created in Netbeans 10.它是在 Netbeans 10 中创建的。

Edit: I also tried add label with position and sieze (setBounds) it doesn't help.编辑:我也尝试添加 label 和 position 和 sieze (setBounds) 它没有帮助。 I changed the code with setBounds method.我用 setBounds 方法更改了代码。

First, main class in JavaTestApp.java:一、JavaTestApp.java中主要的class:

package javatestapp;

public class JavaTestApp {
    public static void main(String[] args) {
        TestForm mainFrame = new TestForm();

        mainFrame.setLocation(300, 150);
        mainFrame.setVisible(true);

        mainFrame.toFront();
        mainFrame.repaint();
    }

}

Second file is:第二个文件是:

package javatestapp;

import javax.swing.JLabel;

public class TestForm extends javax.swing.JFrame {

    /**
     * Creates new form TestForm
     */
    public TestForm() {
        initComponents();

        JLabel label = new JLabel("Test label");
        label.setBounds(10,10,100,25);        

        getContentPane().add(label);
    }

    // GENERATED CODE BELOW
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        pack();
    }// </editor-fold>                        

    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(TestForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(TestForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(TestForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(TestForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new TestForm().setVisible(true);
            }
        });
    }

Stacktrace, regarding to @VGR request: Stacktrace,关于@VGR 请求:

Exception in thread "main" java.lang.IllegalArgumentException
    at org.netbeans.lib.awtextra.AbsoluteLayout.addLayoutComponent(Unknown Source) 
    at java.awt.Container.addImpl(Container.java:1120)
    at java.awt.Container.add(Container.java:410)
    at javatestapp.TestForm.<init>(TestForm.java:16)
    at javatestapp.JavaTestApp.main(JavaTestApp.java:5) 
BUILD STOPPED (total time: 9 seconds)

Link to project uploaded on weetransfer: Project (scanned via my Bitdefender antivir)链接到在 weetransfer 上上传的项目: 项目(通过我的 Bitdefender antivir 扫描)

I also chosen absolute layout我也选择了绝对布局

And that is your problem.那是你的问题。 You are not using it correctly.您没有正确使用它。

    getContentPane().add(label);

You can't just add the label to the frame without specifying the proper constraints.您不能只将 label 添加到框架而不指定适当的约束。 I've never used AbsoluteLayout (because I believe in proper layout management) but I would guess you need to specify constraints like x, y, width, height.我从未使用过 AbsoluteLayout(因为我相信正确的布局管理),但我猜您需要指定 x、y、宽度、高度等约束。

The layout manager can't guess where you want to position the component so you need to specify all the information.布局管理器无法猜测您想要 position 组件的位置,因此您需要指定所有信息。 That is why you should be using a layout manager.这就是您应该使用布局管理器的原因。 Then the layout manager will position the component based on the rules of the layout manager.然后布局管理器将根据布局管理器的规则 position 组件。 Much easier, once you practice it a little.简单多了,只要稍微练习一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM