简体   繁体   English

JLabel不会更改宽度

[英]JLabel wont change Width

I'm programming right now a Chomp Game for Uni. 我现在正在为Uni编写Chomp游戏。 Everything works fine but the Label at the bottom. 一切正常,但标签在底部。 Its background is supposed to fill out the entire bottom. 它的背景应该填满整个底部。 In the attachment you can see how it instead looks now. 在附件中,您现在可以看到它的外观。 I tried setting the minimum and the preferred size of the label. 我尝试设置标签的最小尺寸和首选尺寸。 The Height is changing but the width just stays adjusted to the text. 高度在变化,但宽度仅根据文本进行调整。 How can I change that? 我该如何改变?

Note: The snippet only contains the setting up of the Frame and Panels in a custom method and not the main class. 注意:该代码段仅包含自定义方法中的“框架”和“面板”设置,而不包含主类。

private void init()
    {
    JFrame fenster = new JFrame();
    this.spielfeld = new SpielfeldPanel(M, N);
    this.anzeige = new SpielerAnzeigeLabel(this.spieler);
    JPanel panel = new JPanel();
    BoxLayout boxlayout = new BoxLayout(panel,BoxLayout.Y_AXIS);
    panel.setLayout(boxlayout);
    fenster.setTitle("Chomp");
    fenster.setSize(1000,700);

    panel.setPreferredSize(new Dimension(1000, 60));
    Dimension d = new Dimension(getPreferredSize());
    panel.setMinimumSize(d);
    panel.add(spielfeld);
    panel.add(anzeige);
    fenster.add(panel);


    this.spielfeld.setVisible(true);
    this.anzeige.setVisible(true);
    panel.setVisible(true);
    fenster.setVisible(true);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);




    }

http://i.stack.imgur.com/qDfBM.png

A BoxLayout respects the width of the component to the label is displayed at its preferred width/height. BoxLayout尊重组件到标签的宽度,并以其首选的宽度/高度显示。

A JFrame uses a BorderLayout by default. 默认情况下,JFrame使用BorderLayout。 So just add the label to the frame independently of the panel: 因此,只需将标签独立于面板添加到框架即可:

//panel.add(anzeige);
//fenster.add(panel);
fenster.add(panel, BorderLayout.CENTER);
fenster.add(anzeige, BorderLayout.PAGE_END);

The PAGE_END constraint respects the height but makes the width equal to the space available. PAGE_END约束尊重高度,但使宽度等于可用空间。 Read the section from the Swing tutorial on How to Use BorderLayout for more information and examples. 阅读Swing教程中有关如何使用BorderLayout的部分, 获取更多信息和示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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