[英]Calling super.paintcomponent(g) in class doesn't work
在我问这个问题之前,我已经检查了其他人的问题,看看是否有人可以解决,我已经尝试了一些,但是没有用。 我问你,也许我的程序还需要其他东西。
谁能告诉我这么小的代码和平怎么了?
package DrawPanel;
import java.awt.Graphics;
import javax.swing.JPanel;
public class DrawPanel
{
private int getHeight()
{ return 0; }
private int getWidth()
{ return 0; }
public void paintComponent(Graphics g)
{
super.paintComponent(g); // line of error => paintComponent
int width = getWidth();
int height = getHeight();
g.drawLine(0, 0,width,height);
g.drawLine(0, height, width, 0);
}
}
还有其他代码可以运行它:
package DrawPanel;
import java.awt.Component;
import javax.swing.JFrame;
public class DrawPanelTest
{
public static void main ( String [] Args)
{
DrawPanel panel = new DrawPanel();
JFrame application = new JFrame();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
application.add(panel); //Line of error => add
application.setSize(500,500);
application.setVisible(true);
}
}
现在,如果我删除错误行,则该应用程序将运行,但不能100%运行。 它不会显示我所做的画线。 它只会打开我一个窗口。 如何使应用正常运行?? 谢谢。
public class DrawPanel extends JPanel
{
public void paintComponent(Graphics g)
{
super.paintComponent(g);
int width = getWidth();
int height = getHeight();
g.drawLine(0, 0,width,height);
g.drawLine(0, height, width, 0);
}
}
您应该扩展JPanel
super
是指直系父母的财产。 因此,在您的情况下,您不能调用super,因为DrawPanel没有父母。 您可以通过添加extends JPanel
来解决该问题,这还将解决main
方法中的.add()
问题。 .add()需要一个Component
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.