2014-03-01 38 views
0

我想弄清楚如何在学习Java GUI基础知识的同时在Swing GUI面板中使用DrawPolygon。在Swing GUI面板中绘制多边形Java

这是用于产生摆动GUI的面板的代码:

polygonArea = new javax.swing.JPanel(){ 
     protected void poly(Graphics g) { 
     int xpoints[] = {35, 10, 25, 60, 20}; 
int ypoints[] = {105, 25, 5, 105, 25}; 
int xpoints2[] = {60, 70, 92, 80, 82}; 
int ypoints2[] = {105, 25, 5, 105, 25}; 
int xpoints3[] = {102, 98, 145, 107}; 
int ypoints3[] = {5, 105, 105, 100}; 
int npoints = 5; 
int npointsl = 4; 

g.fillPolygon(xpoints, ypoints, npoints); 
g.fillPolygon(xpoints2, ypoints2, npoints); 
g.fillPolygon(xpoints3, ypoints3, npointsl); 
     } 
    }; 
    polygonArea.setBackground(new java.awt.Color(240, 240, 240)); 

基于从关闭Netbeans的生成的GUI。我真的很新的Java,但是当我启动该文件看起来是这样的:

enter image description here

http://i.stack.imgur.com/4KsIo.jpg

而是自身聚功能,显示的:

enter image description here

http://i.stack.imgur.com/XrAsK.png

对不起,如果它是一个漂亮的obvio我们的错误,任何帮助将不胜感激!

(不能发表由于口碑图片)

回答

4

方法poly没有在Swing中的油漆栈自动调用。您需要例如从JPanel的,paintComponent(Graphics g)明确地做到这一点

class PolyPanel extends JPanel { 
    protected void poly(Graphics g) { 
     ... 
    } 

    @Override 
    protected void paintComponent(Graphics g) { 
     super.paintComponent(g); 
     poly(g); 
    } 
} 
+0

谢谢你的回应,它说它找不到符号JComponent?再次抱歉,如果这是简单的我错过了,谢谢! –

+0

实际上'JComponent'本身并不做任何自定义绘画,所以它最容易坚持使用'JPanel'作为背景颜色,已经删除了那个脚注:) – Reimeus

+0

这就是问题所在,我导入了javax.swing。*,但它没有没有工作。为javax.swing.JComponent添加一个导入可以解决这个问题。谢谢! –

0

覆盖功能,并呼吁从中poly(Graphics g)。像这样的:

public void paintComponent(Graphics g) { 
    super.paintComponent(g); 
    poly(g); 
}