我试图弄清楚如何在学习Java GUI的基础时在Swing GUI的面板中使用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真的很陌生,但是当我启动文件时,它看起来像这样:
http://i.stack.imgur.com/4KsIo.jpg
而不是单独显示的poly函数:
http://i.stack.imgur.com/XrAsK.png
抱歉,如果这是一个非常明显的错误,我们将不胜感激!
(由于声誉原因,无法发布图片)
最佳答案
方法poly
不会在Swing的绘画堆栈中自动调用。例如,您需要明确地执行此操作
class PolyPanel extends JPanel {
protected void poly(Graphics g) {
...
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
poly(g);
}
}