Question

So I have a JPanel called displayPane and I want to make it a drawing area for a graph (I am making a graphing calculator). I am using WindowBuilder and this is the generated code for the JPanel:

JPanel displayPane = new JPanel();
displayPane.setBackground(Color.WHITE);
displayPane.setBounds(173, 33, 455, 432);
frame.getContentPane().add(displayPane);

After that I want to draw the axis of the graph but I have no idea how. I've searched everywhere about it but everyone constructs a member class or something in the main class and adds the paintComponent(Graphics g) but that confuses me. What is that trying to accomplish ? Or just give me your way of doing it I don't really care as long as I understand it. Any help is appreciated :)

Was it helpful?

Solution

Since this is homework, I'm going to give you general guidance without code, but first and foremost, please read this link on performing custom painting with Swing. Next you should put the Window Builder software to the side and work on creating your own code from scratch, at least do this til you're comfortable coding with Swing.

Next suggestions:

  • Have your DrawingPanel extend JPanel
  • Override paintComponent(Graphics g)
  • Call the super's method in your override, super.paintComponent(g) as this will refresh the graphics and erase old "dirty" pixels.
  • Play with drawing lines using g.drawLine(...)`
  • keep doing this and you'll get the idea of what you'll need.

OTHER TIPS

Custom painting is achieved by overriding the paintComponent method of a JComponent based class (like JPanel).

This gives you access to the drawing surface onto which content is drawing and eventually shown on screen

See Custom painting and Painting in AWT and Swing for more details.

The Graphics API (or more specifically, the Graphics2D API) is a power abstract toolkit which provides with the means to actually paint stuff to the screen.

At the basic level, this provides you with the ability to specify colors and draw basic shapes and text. At a more complex level, you can define you own shapes, perform more complex coloring effects, including gradient fills and transformations of the basic context

See the 2D Graphics Trail for more details.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top