我在阅读 Core Java 时遇到了以下代码片段:
package draw;
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class DrawTest
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
JFrame frame = new DrawFrame();
frame.setTitle("DrawTest");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class DrawFrame extends JFrame
{
public DrawFrame()
{
add(new DrawComponent());
pack();
}
}
class DrawComponent extends JComponent
{
private static final int DEFAULT_WIDTH = 400;
private static final int DEFAULT_HEIGHT = 400;
public void paintCompent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
// draw a rectangle
double leftX = 100;
double topY = 100;
double width = 200;
double height = 150;
Rectangle2D rect = new Rectangle2D.Double(leftX, topY, width, height);
g2.draw(rect);
// draw the enclosed ellipse
Ellipse2D ellipse = new Ellipse2D.Double();
ellipse.setFrame(rect);
g2.draw(ellipse);
// draw a diagonal line
g2.draw(new Line2D.Double(leftX, topY, leftX + width, topY + height));
// draw a circle with the same center
double centerX = rect.getCenterX();
double centerY = rect.getCenterY();
double radius = 150;
Ellipse2D circle = new Ellipse2D.Double();
circle.setFrameFromCenter(centerX, centerY, centerX + radius, centerY + radius);
g2.draw(circle);
}
public Dimension getPreferredSize()
{
return new Dimension(DEFAULT_WIDTH, DEFAULT_HEIGHT);
}
}
我在 Eclipse 上尝试了这段代码,它确实运行了,但是框架中没有出现矩形、椭圆、对角线和圆形,而是什么都没有出现。我对照书上的代码仔细检查了一遍,没有错别字。怎么了?
最佳答案
有一个拼写错误...
public void paintCompent(Graphics g) {
应该是
public void paintComponent(Graphics g) {
这就是为什么您应该使用@Override
注释,因为当您尝试覆盖父层次结构中不存在的方法时,它会给您一个编译时错误。
在执行任何自定义绘画之前,您还应该调用 super.paintComponent(g);
关于java - Core Java 中的绘制形状示例未出现在框架中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24858978/