这是我制作的一个测试程序,这样我就可以使用 Polygon 进行练习,但即使在最小化并重新打开窗口后,框架中也没有显示任何内容。这不是我第一个使用 JFrame 的程序,但在制作这个程序后,我注意到前一个程序也有同样的问题,只是另一个程序有时会正确显示所有内容
import javax.swing.JFrame;
import javax.swing.JComponent;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Color;
import java.awt.Polygon;
import java.awt.Rectangle;
class GraphicComponent extends JComponent
{
public void PaintComponent(Graphics g)
{
Graphics2D g2 = (Graphics2D) g;
int x[] = {10,20,40,40,50,70,80,60,20,20};
int y[] = {20,0,0,80,80,65,80,100,100,20};
Polygon poligono1 = new Polygon(x, y, 10);
g2.draw(poligono1);
Rectangle rectangulo = new Rectangle(5, 30, 100, 200);
g2.fill(rectangulo);
}
}
public class PracticaPoligonos
{
public static void main(String args [])
{
JFrame marco = new JFrame();
marco.setSize(640, 480);
marco.setTitle("Practica polygon");
marco.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GraphicComponent grafico = new GraphicComponent();
marco.add(grafico);
marco.setVisible(true);
}
}
paintComponent
,而不是PaintComponent
。
Override
进行注释,编译器会引起您的注意。
class GraphicComponent extends JComponent
{
@Override // ⬅️ Annotate, to communicate your intentions to the compiler.
public void paintComponent(Graphics g) // ⬅️ Lowercase letter starts a method name. Method names are case-sensitive.
{
Graphics2D g2 = (Graphics2D) g;
…