gpt4 book ai didi

Java 图形错误 : Static/Nonstatic mishap

转载 作者:行者123 更新时间:2023-11-29 08:50:40 25 4
gpt4 key购买 nike

所以,我正在做一个插槽项目,因为我想熟悉 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com