简体   繁体   中英

JPanel won't add the JLabel text?

class Gui {

    protected JFrame j = new JFrame("My First window");
    protected JPanel p = new JPanel();
    protected Container c;
    private GridBagConstraints g = new GridBagConstraints();

    public Gui() {
        j.setSize(350, 250);
        p.setSize(j.getSize());
        this.c = j.getContentPane();
    }

    public void createMyGui() {
        p.setLayout(new GridBagLayout());
        c.add(p);
        setButtons();
        setGuiBackground();
        j.setVisible(true);
        p.setVisible(true);

    }

    private void setGuiBackground() {
        p.setBackground(Color.black);
    }

    private void setButtons() {     
    }

    private void setLabels() {
        g.fill = GridBagConstraints.HORIZONTAL;
        g.ipady = 40;
        g.weightx = 5.0;
        g.insets = new Insets(0,0,0,0);
        g.gridwidth = 3;
        g.gridx = 0;
        g.gridy = 1;    
        JLabel l1 = new JLabel("<html>Text color: <font color='red'>Red!</font>");
        p.add(l1, g);           
    }
}

Basically, the gui just opens a window, with a black background, as I wanted, but it does not show up the text. I've been on a SO question, for setting up a text on a GUI, and it says to use JLabel, and HTML to style the text.

What is wrong with this? Why won't the text show up?

You haven't called setLabels(); . You might have to change the following method into:

public void createMyGui() {
    p.setLayout(new GridBagLayout());
    c.add(p);
    setButtons();
    setGuiBackground();
    setLabels();
    j.setVisible(true);
    p.setVisible(true);
}

This works, I got rid of the container and call the setLabels()

class Gui{

protected JFrame j = new JFrame("My First window");
protected JPanel p = new JPanel();
private GridBagConstraints g = new GridBagConstraints();

public Gui() {
    j.setSize(350, 250);
    p.setSize(j.getSize());
    j.setContentPane(p);
    createMyGui();
    j.setVisible(true);
    p.setVisible(true);
}

public void createMyGui() {
    p.setLayout(new GridBagLayout());
    setButtons();
    setLabels();
    setGuiBackground();
}

private void setGuiBackground() {
    p.setBackground(Color.WHITE);
}

private void setButtons() {     
}

private void setLabels() {
    g.fill = GridBagConstraints.HORIZONTAL;
    g.ipady = 40;
    g.weightx = 5.0;
    g.insets = new Insets(0,0,0,0);
    g.gridx = 0;
    g.gridy = 1;    
    JLabel l1 = new JLabel("<html>Text color: <font color=red>Red!</font></html>");
    p.add(l1, g);           
}

public static void main(String[] args){
    standard s = new standard();
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM