The Need To Restore Graphics Original State When Overwritten paint or paintComponent

前端 未结 2 1781
情书的邮戳
情书的邮戳 2021-02-06 02:27

I realize most of the Java code to overwritten paint or paintComponent, most of them doesn\'t restore the old state of graphics object, after they had change the state of graphi

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-06 02:51

    You should not alter the Graphics object passed in at all, rather perform all your graphics operations on a copy of it which you then dispose. There'll be no need to reset the state at all then.

    public void paintComponent(Graphics g1) {
        super.paintComponent(g1);
        final Graphics2D g = (Graphics2D)g1.create();
        try {
             // ...Whole lotta drawing code...
        } finally {
             g.dispose();
        }
    }
    

提交回复
热议问题