Search code examples
javaswingjpanelpaintcomponent

drawString() won't draw


As it stands I'm trying to draw a string off a component into a frame, the SSCCE would be something like this:

// The component class through which I draw the string!
package gui;

import java.awt.Color;
import java.awt.Graphics;

import javax.swing.JPanel;
import javax.swing.border.LineBorder;

public class PanelEstado extends JPanel{

    private String valores = "";

    protected void paintComponent(Graphics g){

        super.paintComponent(g);
        g.setColor(Color.BLACK);

        g.drawString(valores, 400, 45);

    }

    public void setValores(int arca, int puntosBelleza, int cantidadHabitantes, int cantidadHabitantesDisponibles){

        String valores = "Arca: " + arca 
                + "                                    " 
                + " Puntos de Belleza: " + puntosBelleza + 
                "                                    " + 
                " Habitantes: " + 
                cantidadHabitantes + " / " 
                + cantidadHabitantesDisponibles;
    }

    public PanelEstado(){
        setBorder(new LineBorder(Color.RED));
    }


}

// The Main GUI Class!

public GUIJuego(){

    JPanel panelConstruccion = new JPanel(new GridLayout(9,1));
    JPanel panelDatosCiudad = new JPanel(new GridLayout(1,2));
    JPanel panelMapa = new JPanel(new GridLayout(25,25));
    PanelEstado panEst = new PanelEstado();
        add(panelConstruccion, BorderLayout.WEST);

    add(panelDatosCiudad, BorderLayout.NORTH);
    panelDatosCiudad.add(labelConstrucciones);
    panEst.setValores(administrador.getCiudad().getArca(), administrador.getCiudad().getPuntosBelleza(), administrador.getCiudad().getCantidadHabitantes(), administrador.getCiudad().getCantidadHabitantesDisponibles());
    panelDatosCiudad.add(panEst);
    add(panelMapa, BorderLayout.CENTER);
}

Let me narrow your search down a bit. The most important part of this would be the first class in the SSCCE and this:

    panEst.setValores(administrador.getCiudad().getArca(), administrador.getCiudad().getPuntosBelleza(), administrador.getCiudad().getCantidadHabitantes(), administrador.getCiudad().getCantidadHabitantesDisponibles());
    panelDatosCiudad.add(panEst);

Now, as it stands, the border within the constructor of my Component does show up and is right where I want it to be, but the String that I want to draw is nowhere to be seen. Am I missing something, or doing something wrong?

Thanks,


Solution

  • You didn't override the getPreferredSize() method of the PanelEstado class, so the size is zero so the component is never painted.

    Why are you even using a panel for this. What is wrong with a JLabel and the using the setText(...) method. Then you don't need to worry about setting the preferred size.