JPanel color adjustment issues

Here my canvas class extends 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 call 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 default color oval. I also tried without this., and then tried setting the color band setting the color inside the constructor, but none of them worked. What's wrong?

EDIT: Sorry for not understanding, my goal was to show a thin black oval on a green background.

+3
source share
2 answers

In the paintComponent method, you do not need to use setBackground to change the color of the JPanel. This should be done outside of paintComponent. paintComponent will probably use the background color before you change it.

, . - , paintComponent :

  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);
}

, - . BLACK GREEN.

, , mouseEntered actionPerformed ..

+2

, , :

, , @vincent. . "Super.paintComponent" , .

, ,

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


    super.paintComponent(g);
    g.setColor(Color.GREEN);
    g.fillOval(0, 0, width, height);
    g.setColor(Color.BLACK);
    g.drawOval(0, 0, width, height);
}

0

Source: https://habr.com/ru/post/1784251/


All Articles