2

我在 JFrame 构造函数中有以下简单代码

    super(name);
    setBounds(0,0,1100,750);
    setLayout(null);


    setVisible(true);

    g = this.getGraphics();
    int[] x =new int[]{65,  122,  77,  20, };
    int[] y =new int[]{226,  258, 341,  310};
    g.setColor(Color.RED);  
    g.drawPolygon (x, y, x.length);
    System.out.println(g);

我在控制台上得到输出:

sun.java2d.SunGraphics2D[font=java.awt.Font[family=Dialog,name=Dialog,style=plain,size=12],color=java.awt.Color[r=255,g=0,b=0 ]]

但是在 JFrame 上没有绘制红色多边形,而只是空白的 JFrame。

为什么 ??

4

2 回答 2

7
  • paint(..)不要覆盖JFrame

  • 而是添加自定义 JPanel覆盖paintComponent(Graphics g)JFrame

  • 不要使用Null/AbsoluteLayout 使用适当的LayoutManager

  • 不要调用实例(不是setBounds(..)JFrame不允许但看不到它与此应用程序相关)

  • 不要忘记使用EDT来创建和更改 GUI 组件:

    javax.swing.SwingUtilities.invokeLater(new Runnable() {
                @Override
               public void run() {
                    Test test = new Test();
               }
    });
    

然后你会做这样的事情:

public class Test {

    /**
     * Default constructor for Test.class
     */
    public Test() {
        initComponents();
    }

    public static void main(String[] args) {

        /**
         * Create GUI and components on Event-Dispatch-Thread
         */
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                Test test = new Test();
            }
        });
    }

    /**
     * Initialize GUI and components (including ActionListeners etc)
     */
    private void initComponents() {
        JFrame jFrame = new JFrame();
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        jFrame.add(new MyPanel());

        //pack frame (size JFrame to match preferred sizes of added components and set visible
        jFrame.pack();
        jFrame.setVisible(true);
    }
}

class MyPanel extends JPanel {

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        int[] x = new int[]{65, 122, 77, 20};
        int[] y = new int[]{226, 258, 341, 310};
        g.setColor(Color.RED);
        g.drawPolygon(x, y, x.length);
    }

    //so our panel is the corerct size when pack() is called on Jframe
    @Override
    public Dimension getPreferredSize() {
        return new Dimension(400, 400);
    }
}

产生:

在此处输入图像描述

于 2012-10-25T19:13:32.190 回答
2

您应该更好地覆盖paint(Graphics g)paintComponent(Graphics g)比您正在尝试的方法。在代码中添加下面的行并删除后面的行setVisible

public void paint(Graphics g) {
  int[] x =new int[]{65,  122,  77,  20};
  int[] y =new int[]{226,  258, 341,  310};
  g.setColor(Color.RED);  
  g.drawPolygon (x, y, x.length);
}
于 2012-10-25T19:04:12.460 回答