如何解决错误“未为帧类型定义方法setDefaultCloseOperationint”
我正在使用Visual Studio Code 2020,它给我错误“对于类型为Frame的方法setDefaultCloseOperation(int)未定义”
问题出在第52行,
import java.awt.Frame;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.JFrame;
import java.awt.Color;
public class Main {
public static void main(String[] args) {
boolean loop = false;
/* while (loop = true) {
try {
Thread.sleep(2000);
} catch (InterruptedException reallyIgnored) {}
System.out.println("Loop is working.");
} */
}
static class GraphicsEngine extends Component {
public void paint(Graphics g) {
// Creating Graphics Shortcut
Graphics2D g2d = (Graphics2D)g;
// Creating new framw window,declaring size
Frame frame = new Frame();
frame.add(new GraphicsEngine());
int frameWidth = 700;
int frameHeight = 500;
frame.setSize(frameWidth,frameHeight);
frame.setLayout(null);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.pack();
/* Next part will create dot that moves across screen.
It will have a loop that draws the dot,and also a loop
that erases the previous dot. */
g2d.SetColor(new Color(255,255,255));
g2d.fillRect(0,getSize().height-1,getSize().height-1);
}
}
}
我试图寻找答案,但是我发现没有一个起作用。
我是菜鸟,几天前就学习了Java。我不太了解,但是我正在尝试学习图形的工作原理
解决方法
该错误意味着未找到setDefaultCloseOperation(int)
作为对象frame
的方法。这可能是因为框架对象中没有使用该名称的方法,或者,如果存在这样的方法,则没有一个方法会接受单个int参数。
在此处查找用于Frame和JFrame的API: https://docs.oracle.com/javase/7/docs/api/java/awt/Frame.html https://docs.oracle.com/javase/7/docs/api/javax/swing/JFrame.html
setDeaultCloseOperation似乎是为JFrame对象而不是Frame定义的。 JFrame扩展了Frame,这意味着它是一种特定的框架。具体来说,它是具有setDefaultOperation()
方法的框架。
也许将帧定义更改为Frame frame = new JFrame();
或JFrame frame = new JFrame();
您的标签显示您正在询问有关JFrame的信息,该框架确实具有setDefaultCloseOperation(...)
方法。
但是,您的代码使用的是Frame
,它是AWT组件,而不是Swing组件。使用JFrame
进行摇摆。
此外,您的课程正在扩展Canvas
。对于Swing应用程序,您应该扩展JPanel
并覆盖paintComponent()
。
使用Swing时无需使用AWT组件。
我正在尝试学习图形的当前工作方式
首先,您永远不要在绘画方法中创建组件。绘画方法只能使用Graphics对象进行绘画。
请阅读Custom Painting的Swing教程中的部分,以获取入门的实用示例。
按照教程中的示例获取结构正确的代码。您在此处发布的代码大多是错误的。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。