【问题标题】:Draw Polygon within Panel of Swing GUI Java在 Swing GUI Java 的面板中绘制多边形
【发布时间】:2014-04-02 23:18:27
【问题描述】:

在学习 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

抱歉,如果这是一个非常明显的错误,任何帮助将不胜感激!

(由于声誉问题,无法发布图片)

【问题讨论】:

    标签: java swing user-interface drawing


    【解决方案1】:

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

    class PolyPanel extends JPanel {
        protected void poly(Graphics g) {
           ...  
        }
    
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            poly(g);
        }
    }
    

    【讨论】:

    • 谢谢您的回复,它说找不到符号JComponent?再次抱歉,如果我遗漏了一些简单的东西,谢谢!
    • 其实JComponent本身并没有做任何自定义绘画,所以最容易坚持使用JPanel作为背景颜色,已经删除了那个脚注:)
    • 这正是问题所在,我已经导入了 javax.swing.* 但它不起作用。出于某种原因,为 javax.swing.JComponent 添加导入修复了此问题。谢谢!
    【解决方案2】:

    覆盖 JPanel 中的函数 paintComponent(Graphics g) 并从中调用 poly(Graphics g)。像这样的:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-29
      • 2013-02-17
      • 1970-01-01
      相关资源
      最近更新 更多