在Swing GUI Java面板中绘制多边形

时间:2014-03-01 21:52:10

标签: java swing user-interface drawing

我正在尝试弄清楚如何在学习Java GUI基础知识的同时在Swing GUI的Panel中使用DrawPolygon。

这是用于生成Swing 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

很抱歉,如果这是一个非常明显的错误,任何帮助都会非常感激!

(由于声誉而无法发布图片)

2 个答案:

答案 0 :(得分:4)

方法poly不会在Swing的绘图堆栈中自动调用。您需要明确地执行此操作,例如

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

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

答案 1 :(得分:0)

从JPanel覆盖该功能,paintComponent(Graphics g)并从中调用poly(Graphics g)。像这样:

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