我尝试运行此代码以使用JFrame
主要课程
import java.awt.*;
import javax.swing.JFrame;
public class main {
public static void main(String[] args){
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setTitle("kek");
f.add (new GraphicsSurface());
f.setSize(512, 512);
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}
GraphicsSurface类
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JComponent;
public class GraphicsSurface extends JComponent {
public GraphicsSurface() {
}
public void paint (Graphics g) {
int end = 0;
long redint = 0, greenint = 0, blueint = 0;
int xstart = 0, ystart = 0, xend = 0, yend = 0;
double y = 0, x = 0;
double width = 80;
double angle = 0;
double endpoint = 255;
double curveintensitya = 1.4, curveintensityb = -0.9;
double curvestarta = 30, curvestartb = 150;
double curvelengtha = 15, curvelengthb = 30;
double redvalue = 0, greenvalue = 0, bluevalue = 0;
while (end == 0) {
Graphics2D g2d = (Graphics2D) g;
redvalue = 100 + (y / 2.56);
greenvalue = 50 + (y / 1.28);
bluevalue = 200 + (y / 5.12);
redint = Math.round(redvalue);
greenint = Math.round(greenvalue);
blueint = Math.round(bluevalue);
if (y >= curvestarta && y < (curvestarta + curvelengtha)) {
angle = angle + (curveintensitya / curvelengtha);
}
if (y >= curvestartb && y < (curvestartb + curvelengthb)) {
angle = angle + (curveintensityb / curvelengthb);
}
width = width + angle;
if (width > 512) {
width = 512;
}
x = Math.round(width);
xend = (int) x;
ystart = (int) y;
yend = ystart;
y = y + 1;
if (y > endpoint) {
end = 1;
}
g2d.setColor(new Color(redint, greenint, blueint, 255));
g2d.drawLine(xstart, ystart, xend, yend);
}
}
}
但我在控制台中得到了这个:
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
我想知道导致问题的原因以及解决问题的方法。
答案 0 :(得分:2)
问题在于这一行
g2d.setColor(new Color(redint, greenint, blueint, 255));
代码中 redint,greenint 和 blueint 的类型属于long
类型。但Color
的构造函数包含int
或long
。
您可以参考文档here
解决问题的方法是:将这些类型从long
更改为int
并进行适当的投射。