在我问这个问题之前,我已经检查了其他人的问题,看看是否有人有解决方案,我尝试了一些,但它没有用。而且我问你,我的程序可能需要的东西比其他程序还要多。
任何人都可以告诉我这段代码的小和平有什么问题吗?
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%。 它不会显示我所做的画线。它会打开我只有一个窗口。如何让应用程序正常工作? 谢谢。
答案 0 :(得分:4)
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
来解决此问题,这也将解决.add()
方法中的main
问题。 .add()需要Component