我对java图形还是新手,我写了这段小代码,但它在屏幕上没有显示任何内容。有人可以告诉我出了什么问题吗? 我没有收到任何错误,但它只是没有显示任何内容。谢谢
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import javax.swing.*;
public class GraphicsExample extends JPanel {
public void paintComponenet(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g.setColor(Color.red);
g.drawRect(10, 10, 200, 200);
for(int i=0; i<20; i++){
g.setColor(new Color((int) (Math.random() *255), (int)(Math.random()*255),(int) (Math.random()*255)));
g.fillOval(20+(int)(Math.random()*180), 20+(int)(Math.random()*180), 5, 5);
}
g.setColor(Color.red);
g.drawString("Hello there", 20, 20);
}
public static void main(String[] args) {
JFrame f = new JFrame();
f.add(new GraphicsExample());
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setSize(400,600);
f.show();
}
}
最佳答案
paintComponenet
拼写错误,应该是 paintComponent
当您“认为”要重写方法时,请首先使用@Override
注释...
@Override
public void paintComponenet(Graphics g) {
如果编译器在父类中找不到相应的方法,这将导致编译器错误,这将突出显示这些类型的错误...
@Override
public void paintComponent(Graphics g) {
关于java - PaintComponent 和 java 图形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30069209/