-1

When I try to add anything to JFrame in constructor and I have IllegalArgumentException.

Similar code is working in documentation: https://docs.oracle.com/javase/tutorial/uiswing/layout/none.html

Why my very simple code doesn't work? It is created in Netbeans 10.

Edit: I also tried add label with position and sieze (setBounds) it doesn't help. I changed the code with setBounds method.

First, main class in JavaTestApp.java:

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:

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)

arrowman
  • 424
  • 6
  • 19
  • I feel that I need any good advice which leads me correct way to learn Java SE and Swing. I have read many tutorials and topics. Adding new components is common thing like in documentation linked above. It has to be simple. So I have to not undertand something. I would be glad if you could propose me maybe better course than documentation on Oracle and topics on this forum and many videos on Youtube ? – arrowman Nov 13 '19 at 22:50
  • Most people with similar IllegalArgumentException had problem when they tried to: - adding JFrame to JFrame or JPanel, - adding not initalized variable to JFrame pane, - used layouts like Flow which needs one more argumment (aligment or somethin similar, i.e. FLowLayout.CENTER), - I am sure it was more cases. I have read many topics on Google, it took me days. Nothing help. – arrowman Nov 13 '19 at 22:52
  • 1
    Well, the first advice is stop using the GUI Builder and write your code "by hand", `Absolute Layout` is the same as `null-layout` and will cause you issues like [this one](https://stackoverflow.com/a/42521097/2180785) in the future when testing in another computer with different OS / PLAF / screen size or resolution / etc. Second advice is post the stack trace. And third is don't extend `JFrame`, you're not changing its behavior, so just create an instance of it. – Frakcool Nov 13 '19 at 22:53
  • @Frakcool thanks! I wathed and read many tutorials about layout. Every has only simple excamples. I need more complex layout. Some guys propose using Panels with separate layouts.They didn't show how to do this and what layout shout be declared for main JFrame window. This guy from link you proposed have different problem. He don't have IllegalArgumentException (why he doesn't?) He add some components succesfully. I also defined bounds (location and sizes) like he and it doesn't help. What is the difference betwen my code and his? I dunno understand. – arrowman Nov 13 '19 at 22:59
  • I also chosen absolute layout because I want to write own responsive mechanism for windows and components. I checked all layouts in Netbeans and no one is responsive like in web (I usually use HTML, CSS, PHP, Javascript). Thses layouts are terrible useless comparing to web technologies. Like before dinosaurs! This logic is completly different comparng to web which is logic at all. Is this any solution for responsive GUI in JavaSE? – arrowman Nov 13 '19 at 23:04
  • 1
    Layout management is a complex subject, but with some time and practice, you can do some outstanding things. For [example](https://stackoverflow.com/questions/13238884/which-layout-manager-to-use/13240195#13240195), [example](https://stackoverflow.com/questions/26411775/how-i-can-do-swing-complex-layout-java/26412976#26412976), [example](https://stackoverflow.com/questions/18625700/gui-layout-with-swing-components-java/18625728#18625728), [example](https://stackoverflow.com/questions/33576358/how-to-use-java-swing-layout-manager-to-make-this-gui/33577874#33577874) – MadProgrammer Nov 13 '19 at 23:59
  • [example](https://stackoverflow.com/questions/22394845/space-button-size-on-my-layout-keyboard-wont-resize/22395483#22395483) – MadProgrammer Nov 14 '19 at 00:02
  • 1
    Edit your question and include the full stack trace of the exception you’re getting. It will tell us, and you, what is going wrong and where. – VGR Nov 14 '19 at 00:34
  • The link that I provided was not related to `IllegalArgumentException` but to the kind of problems you'll face when using `AbsoluteLayout` or `null-layout`, look at the pictures (before and after). Again, as recommended by camickr on his answer below or in @MadProgrammer's comments above use [Layout Managers](https://docs.oracle.com/javase/tutorial/uiswing/layout/visual.html) and combine them as in his examples or mine – Frakcool Nov 14 '19 at 15:32
  • @arrowman, why did you edit your question. You already have the answer to your problem. Fix your code and "accept" the answer so people know the problem has been solved. – camickr Nov 16 '19 at 16:11

1 Answers1

1

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

The layout manager can't guess where you want to position the component so you need to specify all the information. 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. Much easier, once you practice it a little.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • This reply is answered only partly. The truth - not to use Absolute Layout Not true - giving coordinations and dimensions doesn't help. Genral conclusion is general Absolute Layout weakness which force to change Layout to other. – arrowman Dec 17 '19 at 11:37