作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以,我正在做一个插槽项目,因为我想熟悉 java 图形库。该设置工作得相当完美。然后,我尝试画线测试图形,报错:
engine.java:9: 无法从静态上下文中引用非静态方法 drawLine(int,int,int,int)
java.awt.Graphics.drawLine(1, 2, 11, 12);
^
1 个错误
我听从了 friend 的建议,创建了一个新的 engine
并将其命名为 e
,然后我没有执行 drawloop()
做了 e.drawloop
,但得到了同样的错误。
代码:
import java.awt.Graphics;
import java.awt.Dimension;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class engine{
public void drawloop(){
java.awt.Graphics.drawLine(1, 2, 11, 12);
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
display();
}
});
engine e = new engine();
e.drawloop();
}
public static void display(){
JFrame window = new JFrame("Pinnacle Slots");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setPreferredSize(new Dimension(768, 512));
window.pack();
window.setLocationRelativeTo(null);
window.setVisible(true);
}
}
最佳答案
发生的事情是使用了错误的“绘画”调用。通常,一个人会覆盖内置的 paint() 或 paintComponent() 方法。
与您的代码一起使用的示例:
@Override
public void paint(Graphics g) { //This is where that instance of Graphics comes in
super.paint(g); //necessary for the actual JFrame to paint itself
g.drawLine(startX, startY, endX, endY); //and, very simply, draw the line
}
这将在运行时自动调用,但如果您想再次手动调用它(或在其他位置画线),只需使用
repaint().
此外,一个好的做法是为您的 JFrame 设置一个 contentPane。您可以使用自定义 JPanel/JComponent 或简单地使用
setContentPane(getContentPane());
在 display() 方法中。
我希望这对您和其他人有帮助!
关于Java 图形错误 : Static/Nonstatic mishap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22889139/
所以,我正在做一个插槽项目,因为我想熟悉 java 图形库。该设置工作得相当完美。然后,我尝试画线测试图形,报错: engine.java:9: 无法从静态上下文中引用非静态方法 drawLine(i
我是一名优秀的程序员,十分优秀!