我的这段代码似乎抛出了 IllegalComponentException,但我不确定为什么。归结为以下几行代码:
JRadioButton setRed = new JRadioButton(“Red", true);
JRadioButton setBlue = new JRadioButton("Blue", false);
JRadioButton setYellow = new JRadioButton("Yellow", false);
JPanel options = new JPanel();
options.add(setBlue, BoxLayout.Y_AXIS);//error here
options.add(setRed, BoxLayout.Y_AXIS);//and probably here too
options.add(setYellow, BoxLayout.Y_AXIS);//and here
这是错误:
Exception in thread "main" java.lang.IllegalArgumentException: illegal component position
at java.awt.Container.addImpl(Container.java:1034)
at java.awt.Container.add(Container.java:406)
at DrawCanvas.go(DrawCanvas.java:42)
at DrawCanvas.main(DrawCanvas.java:27)
最佳答案
你的代码没有任何意义。将组件添加到 JPanel 时不使用 BoxLayout 常量,而是在创建 BoxLayout 对象时使用这些常量,这是您尚未完成的操作。
您需要:
- 使用适当的 BoxLayout 常量创建 BoxLayout 对象,并传入对将使用此布局的容器的引用。
- 将 JPanel 的布局设置为此对象
- 将组件添加到 JPanel 而不常量。
- 最重要的是,您需要阅读本教程,因为很明显您在尝试使用此工具时没有首先检查此重要资源。你不能猜测这些东西并期望它起作用。
Google:Java BoxLayout 教程
。第一击。
关于java - BoxLayout 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23981160/