Problems drawing an oval in a panel (JAVA)

5

Greetings dear programmers friends.

I'm running into a somewhat annoying error: Cogito draw a graph on the screen using circular / oval shapes. After a good number of searches, I was suggested to use a class that extended JPanel / JComponent (tested with both) , and used a painting method using Graphics, which was called by paintComponent.

I did this in many ways, and at the end of the day, the same thing persists: Squares painted white.

Itisbeingdrawnthiswaytoday.Iwouldlikethepanelstobecomecircles.

This is the code I use to do such a thing. I described the comments for ease of viewing.

Here is the class I created based on the 300 examples of drawOval in Java.

public class Bolinha extends JPanel{


public void pintar(Graphics g){
    g.setColor(Color.white);
    g.fillOval(50, 50, 20, 20);
}

@Override
protected void paintComponent(Graphics g) {
    pintar(g);
    super.paintComponent(g);
}

Unfortunately, I can not post more images, but using this code:

 for (int i = 0; i < g.getListaDeVertices().size(); i++){
        v1 = g.getListaDeVertices().get(i); //Pega o vértice
        Bolinha bola = new Bolinha();
        bola.setSize(30, 30);
        bola.setLocation(v1.getPosX(), v1.getPosY() + 180);
        bola.setVisible(true);
        bola.setBackground(Color.white);
        bola.add(new Label(Integer.toString(g.getListaDeVertices().get(i).getIdMatriz())));
        PainelDesenho.add(bola);
        listaDePaineis.add(p);

I just got the same result (squares) instead of balls.

I'm sorry for the lack of other images. Thanks to anyone who can help! A big hug, Momentanius.

    
asked by anonymous 06.10.2015 / 15:40

1 answer

1

From what I noticed, the error is at each node of the graph being a new JPanel . The ball.setBackground (Color.white) function is setting the background of your JPanel to white and therefore a white square.

One solution I can suggest is to create a class called Graph that extends a JPanel . This class will receive as a parameter in its constructor the list of vertices and draw the respective nodes. That is, you will only have one JPanel that will draw all the graph nodes in your JFrame , understood? An example, just to get an idea, what it would look like:

  class Grafo extends JPanel {

  Lista listaDeVertices

  Grafo(Lista listaDeVertices) {

    this.listaDeVertices = listaDeVertices;

    setFocusable(true);
    setDoubleBuffered(true);
    setLayout(new FlowLayout());

    repaint();
    setVisible(true);

  }

  @Override
  public void paint(Graphics g) {

    super.paint(g);
    update(g);

  }

  @Override
  public void update(Graphics g) {

    for(int i = 0; i < listaDeVertices.size(); i++) {

      v1 = listaDeVertices.get(i);
      g.drawOval(v1.getPosX(), v1.getPosY()+180, 30, 30);

    }

  }

}
    
07.10.2015 / 05:01