Java: Create global graphics object

前端 未结 2 1579
青春惊慌失措
青春惊慌失措 2021-01-27 07:07

I\'ve extended the JPanel class to draw a graph. The problem that I\'ve got is that I need a global graphics object in order to call it in multiple methods... As an example, her

相关标签:
2条回答
  • 2021-01-27 07:42

    My suggestion would be this:

    public class Graph extends JPanel {
        public void paintComponent(Graphics g){
            super.paintComponent(g);
            g2d = (Graphics2D) g;
            drawGridLines(g2d, ......);
        }
    
        private void drawGridLines(Graphics2D g2d, int hor, int vert){
            g2d.someLogicToDrawMyGridLines(someparams);
        }
    }
    

    i.e. keep all the uses of your graphics context inside the paintComponent call.

    0 讨论(0)
  • 2021-01-27 08:01

    How would I pass in the graphics object externally?

    Don't. The graphics context is only valid during the invocation of paintComponent(). Instead, use the MVC pattern, discussed here, to update a model that notifies any listening view to render itself. JFreeChart is a complete example.

    0 讨论(0)
提交回复
热议问题