Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with setting JPanel's colour

Here's my canvas class extending JPanel:

package start;

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JPanel;

public class Board extends JPanel
{
    private static final long serialVersionUID = 1L;

    public Board() {}

    public void paintComponent(Graphics g) 
    {
        int width = getWidth();
        int height = getHeight();
        this.setBackground(Color.green);

        g.setColor(Color.black);
        g.drawOval(0, 0, width, height);
    }
}

Here's the method where I'm calling it:

private static void createAndShowGUI() 
{

JFrame frame = new JFrame("Hello");
frame.setPreferredSize(new Dimension(700, 700));

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Board b = new Board();
frame.getContentPane().add(b);

frame.pack();
frame.setVisible(true);
}

But this shows the oval on the default colour. I also tried without the this., and then tried setting the colour of b, and setting the colour inside the constructor, but none of these worked. What's wrong?

EDIT: Sorry for not making thing clear, my goal was to display a thin black oval on a green background.

like image 845
Igor Avatar asked Jan 26 '26 09:01

Igor


1 Answers

In the paintComponent method you do not have to use setBackground to change the colour of the JPanel. That should be done outside of paintComponent. paintComponent will probably use the colour of the background before you change it.

There are a number of things you can try. One, is to set the colour in the constructor and then call the super class' paintComponent first like this:

  public Board() {
         this.setBackground(Color.GREEN);
  }

  public void paintComponent(Graphics g) 
{
    super.paintComponent(g);
    int width = getWidth();
    int height = getHeight();        

    g.setColor(Color.BLACK);
    g.drawOval(0, 0, width, height);
}

Also note the color constants are all upper case. i.e. BLACK or GREEN.

If you want to change the background colour dynamically then you can do so in the event handler such as mouseEntered or actionPerformed etc.

like image 153
Vincent Ramdhanie Avatar answered Jan 27 '26 22:01

Vincent Ramdhanie