我是Java Swing的新学习者。我想画一些形状。
无法理解为什么,有人可以帮助我吗?非常感谢!
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class Draw
{
public static void main(String[] args)
{
EventQueue.invokeLater(new Runnable()
{
public void run()
{
DrawFrame frame = new DrawFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
});
}
}
class DrawFrame extends JFrame
{
public static final int DEFAULT_WIDTH = 400;
public static final int DEFAULT_HEIGHT = 400;
public DrawFrame()
{
setTitle("DrawTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);
DrawComponent component = new DrawComponent();
add(component);
}
}
class DrawComponent extends JComponent
{
public void painComponent(Graphics g)
{
Graphics2D g2= (Graphics2D) g;
Rectangle2D rec = new Rectangle2D.Double(100, 100, 200, 150);
g2.draw(rec);
Ellipse2D ellipse = new Ellipse2D.Double();
ellipse.setFrame(rec);
g2.draw(ellipse);
}
}
答案 0 :(得分:3)
在提供的代码中,paintComponent
方法名称中包含错误:
public void painComponent(Graphics g)
所以它实际上并没有覆盖超类的方法。您可以添加@Override注释,以便在方法实际上不覆盖任何内容时编译器将给出错误,例如:
@Override
public void painComponent(Graphics g)