向JPanel添加带JLabel的JComponent触发IllegalArgumentException问题排查
问题
作为GUI开发新手,我想给按钮、滑块这类组件正确添加标签,于是写了一个LabeledComponent类,它可以给任意JComponent添加标签,还能设置标签在组件的北、东、南、西方向。但执行代码new LabeledComponent<>("Depth", new JSlider(1, 10, 21), LabeledComponent.LabelPosition.North);时触发了IllegalArgumentException,想知道这个异常的原因是什么?是不是泛型使用有问题?相关代码如下:
public class LabeledComponent<E extends JComponent> extends JPanel { public enum LabelPosition { North, South, East, West } public LabeledComponent(String label, E component, LabelPosition position) { JLabel label1 = new JLabel(label); switch (position) { case North -> { setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); add(label1); add(component); } case South -> { setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); add(component); add(label1); } case East -> { setLayout(new FlowLayout()); add(component); add(label1); } case West -> { setLayout(new FlowLayout()); add(label1); add(component); } } } }
原因分析与解决办法
- 异常和泛型无关:你的
LabeledComponent泛型声明<E extends JComponent>是正确的,JSlider属于JComponent子类,符合泛型约束,这部分没有问题。 - 真正原因是JSlider构造参数非法:你创建
JSlider时用了new JSlider(1, 10, 21),这个构造方法的三个参数分别是最小值、最大值、初始值,要求初始值必须在最小值和最大值的范围内(也就是1到10之间),但你传的初始值是21,超出了[1,10]的范围,所以触发了IllegalArgumentException。 - 修正方法:把初始值改成1到10之间的整数即可,比如:
new LabeledComponent<>("Depth", new JSlider(1, 10, 5), LabeledComponent.LabelPosition.North);
内容的提问来源于stack exchange,提问作者smilly
相关产品推荐
相关产品推荐

