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

基本上,gui 只是打开了一个黑色背景的窗口,正如我想要的那样,但它没有显示文本。我一直在问一个 SO 问题,在 GUI 上设置文本,它说使用 JLabel 和 HTML 来设置文本样式。

这有什么问题?为什么文字不显示?

4

2 回答 2

2

你没有打电话setLabels();。您可能必须将以下方法更改为:

public void createMyGui() {
    p.setLayout(new GridBagLayout());
    c.add(p);
    setButtons();
    setGuiBackground();
    setLabels();
    j.setVisible(true);
    p.setVisible(true);
}
于 2013-08-12T11:47:02.030 回答
1

这行得通,我摆脱了容器并调用 setLabels()

桂类{

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

}

于 2013-08-12T12:24:16.977 回答