[英]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.