Search code examples
javaintellij-ideajframejlabel

frame.add (label, JFrame.TOP) error


i get an error of Exception in thread "main" java.lang.IllegalArgumentException: illegal component position. It works when i do frame.add(label, JFrame.CENTER) but when i change it it dosnt work.

package com.java;

import javax.swing.*;

import sun.audio.*;

import java.awt.*;

public class PlayClip extends JFrame{

public static void frame(){
    JFrame frame = new JFrame("COLLIN");
    frame.setSize(1086, 1200);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    ImageIcon image = new ImageIcon("C:MYFILE");
    JLabel label = new JLabel(image);frame.setResizable(false);
    frame.add(label, JLabel.BOTTOM);
    frame.setVisible(true);
}

public static void main(String[] args){
    frame();
}
}

Solution

  • You're using frame.add(label, JLabel.BOTTOM); wrong. The documentation says:

    comp - the component to be added

    index - the position at which to insert the component, or -1 to append the component to the end

    JFrame.CENTER equals 0, by coincidence. That's why it works. TOP and BOTTOM are 1 and 3, respectively. When you use those, it's like getting an index out of bounds error on an array/list.

    You should look into using a layout manager because this method isn't for what you think it's for.


    This proof of concept probably does what you want:

    public static void main(String[] args) {
        JFrame frame = new JFrame("COLLIN");
        frame.setSize(1086, 1200);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JLabel label = new JLabel("my text", SwingConstants.CENTER);
        frame.setResizable(false);
        frame.add(label);
        frame.setVisible(true);
    }