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 只是打开一个窗口,如我所愿,背景为黑色,但它没有显示文本。我一直在回答一个关于在GUI上设置文本的问题,它说要使用JLabel和HTML来设置文本样式。
这有什么问题?为什么文本不显示?
你还没有叫setLabels();
. 您可能需要将以下方法更改为:
public void createMyGui() {
p.setLayout(new GridBagLayout());
c.add(p);
setButtons();
setGuiBackground();
setLabels();
j.setVisible(true);
p.setVisible(true);
}
这行得通,我摆脱了容器并调用了 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();
}
}