java frame.add (label, JFrame.TOP) 错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17220012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 01:20:37  来源:igfitidea点击:

frame.add (label, JFrame.TOP) error

javaintellij-ideajframejlabel

提问by Mubin

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.

我在线程“main”java.lang.IllegalArgumentException:非法组件位置中收到异常错误。当我做 frame.add(label, JFrame.CENTER) 时它起作用,但是当我改变它时它不起作用。

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

回答by Daniel Kaplan

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

你用frame.add(label, JLabel.BOTTOM);错了。文档说:

comp- the component to be added

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

comp- 要添加的组件

index- 插入组件的位置,或 -1 将组件附加到末尾

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

JFrame.CENTER巧合,等于0。这就是它起作用的原因。 TOPBOTTOM分别为 1 和 3。当您使用它们时,就像在数组/列表上获取索引越界错误一样。

You should look into using a layout managerbecause 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);
}

回答by Mubin

In line frame.add(label, JLabel.BOTTOM);you are assigning an alignment option for frame, not for JLabel. So you should use the constants from JFrame, and not JLabel.

在行中,frame.add(label, JLabel.BOTTOM);您正在为 分配对齐选项frame,而不是为JLabel。所以你应该使用来自JFrame, 而不是的常量JLabel

The constants of JLabelare used to align the text inside the label.

的常量JLabel用于对齐标签内的文本。

Use frame.add(label). That should be enough.

使用frame.add(label). 那应该就够了。