gpt4 book ai didi

java - JLabel 不在 JPanel 中截断

转载 作者:行者123 更新时间:2023-11-30 08:18:02 25 4
gpt4 key购买 nike

如果我将 JLabel 放入没有严格边界的 JPanel 中,当 JPanel 的大小时它不会截断文本小于文本。为什么会这样? JPanel 是否应该意识到没有足够的空间并相应地截断文本,而不考虑其布局?

例如,我创建了一个 JFrame 和一个两行一列的 GridLayout。在那里,我在顶部放置了一个带有 FlowLayoutJPanel,在底部放置了一个带有 BoxLayoutJPanel .每个 JPanel 都包含一个 JLabel

简而言之:为什么顶部的 JLabel 不截断其文本?

用图片来证明我的意思: enter image description here enter image description here

同样,这是演示效果的SSCCE:

import javax.swing.*;
import java.awt.*;

public class TruncationTest1
{
public static void main(String[] args)
{
JFrame f = new JFrame("Truncation Test");
JPanel panel = new JPanel(); //Default layout, aka FlowLayout
JLabel label = new JLabel("Try resizing the frame: This will not be truncated for some reason.");
JLabel label2 = new JLabel("However, this JLabel, on the other hand, will become truncated.");
f.setLayout(new GridLayout(2,1));
f.setBackground(Color.BLACK);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.add(panel);
panel.setBackground(Color.WHITE);
panel.add(label);
f.add(label2);
label2.setHorizontalAlignment(JLabel.CENTER);
label2.setForeground(Color.WHITE);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
}

最佳答案

FlowLayout 不会调整其中组件的大小。它显示了具有首选大小的组件。

您需要使用不同的布局代替 FlowLayout 以正确调整大小。例如,您可以将 BorderLayout 与位于 LINE_STARTWEST 的标签一起使用。

关于java - JLabel 不在 JPanel 中截断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27813939/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com