Java: JPanel - Drawing Area 2

To initialize the panel -- Constructor

You can set the attributes of a panel from method where it's created, but if all drawing panels have the same attributes or the attribute can easily be parameterized, it's better to put this information in a constructor. For example, let's assume you want the background to be black and the panel to be 200 pixels wide and 100 pixels high.

class SpaceView extends JPanel {
    //========================================= constructor
    public SpaceView () {
        setPreferredSize(new Dimension(200, 100));
        setBackground(Color.black);
    }
   
    //====================================== paintComponent
    @Override public void paintComponent(Graphics g) {
        super.paintComponent(g);
        . . .
    }
}

To find the size of the drawing area

Use drawing.getWidth() and drawing.getHeight() if you need to know the size of your panel (drawing).

@Override public void paintComponent(Graphics g) {
    //... Draw X on this panel
    super.paintComponent(g);
    int w = getWidth();     // get width of panel.
    int h = getHeight();    // get its height.
    g.drawLine(0, 0, w, h); // upper left to lower right.
    g.drawLine(0, h, w, 0); // lower left to upper right.
}

Add setter methods

A good practice is to write "setter" methods in your new class. These are methods which set some value that paintComponent needs to redraw. The setter methods can also cause the panel to redraw if necessary.

To add mouse and key listeners to the drawing panel

If you want to use the mouse over this panel, you have to add a mouse listener. Similarly with a key listener if you want to get key presses. See