java 的 setColor 导致非法参数异常或断言被跳过
java's setColor results in illegal argument exception or assertions are skipped
我有这段代码(在继承自 JPanel
的 class 中从 paintComponent
调用。
assert(red >= 0);
assert(red <= 255);
assert(green >= 0);
assert(green <= 255);
assert(blue >= 0);
assert(blue <= 255);
Color color = new Color(red, green, blue);
过了一段时间我得到一个异常:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Color parameter outside of expected range: Red
at java.awt.Color.testColorValueRange(Unknown Source)
at java.awt.Color.<init>(Unknown Source)
at java.awt.Color.<init>(Unknown Source)
at display.DrawCanvas.drawLed(DrawCanvas.java:55)
at display.DrawCanvas.paintComponent(DrawCanvas.java:36)
at javax.swing.JComponent.paint(Unknown Source)
DrawCanvas.java:55(第 55 行)是上面代码片段的最后一行。
当所有值都在 0 到 255(包括)之间时,参数超出范围怎么可能?
Java 默认情况下不启用断言。
从命令行传递 -ea
命令行标志以启用断言。
java -ea your.main.ClassHere
从 Eclipse 中,您必须转到特定的 运行 配置并在 "VM Arguments" 中添加 -ea
作为 described here。
来自 IntelliJ,它是相似的。在您特定的 运行 配置中,在 "VM options".
中添加 -ea
不管您的 IDE,目标是让它在 java
之后和主 class 名称之前添加 -ea
以启用断言。
一旦你启用了断言,那么他们会在你得到 IllegalArgumentException
.
之前用 AssertionError
停止你的程序
由于您在评论中指出该值为 int
-- 267
,因此这种特殊情况会起作用。请注意,如果您碰巧有 float
值,那么它们可能会通过大于 1.0f
且小于或等于 255.0f
.
的无效值的断言
我有这段代码(在继承自 JPanel
的 class 中从 paintComponent
调用。
assert(red >= 0);
assert(red <= 255);
assert(green >= 0);
assert(green <= 255);
assert(blue >= 0);
assert(blue <= 255);
Color color = new Color(red, green, blue);
过了一段时间我得到一个异常:
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Color parameter outside of expected range: Red
at java.awt.Color.testColorValueRange(Unknown Source)
at java.awt.Color.<init>(Unknown Source)
at java.awt.Color.<init>(Unknown Source)
at display.DrawCanvas.drawLed(DrawCanvas.java:55)
at display.DrawCanvas.paintComponent(DrawCanvas.java:36)
at javax.swing.JComponent.paint(Unknown Source)
DrawCanvas.java:55(第 55 行)是上面代码片段的最后一行。
当所有值都在 0 到 255(包括)之间时,参数超出范围怎么可能?
Java 默认情况下不启用断言。
从命令行传递
-ea
命令行标志以启用断言。java -ea your.main.ClassHere
从 Eclipse 中,您必须转到特定的 运行 配置并在 "VM Arguments" 中添加
-ea
作为 described here。来自 IntelliJ,它是相似的。在您特定的 运行 配置中,在 "VM options".
中添加
-ea
不管您的 IDE,目标是让它在 java
之后和主 class 名称之前添加 -ea
以启用断言。
一旦你启用了断言,那么他们会在你得到 IllegalArgumentException
.
AssertionError
停止你的程序
由于您在评论中指出该值为 int
-- 267
,因此这种特殊情况会起作用。请注意,如果您碰巧有 float
值,那么它们可能会通过大于 1.0f
且小于或等于 255.0f
.