繁体   English   中英

根据文本调整JButton和其他组件的大小

[英]Resizing JButtons and other components according to text

如何在运行时调整JButton的大小以使其适应setSize给出的文本? 我已经做了一些搜索,这是我到目前为止提出的代码。 这会变成一种实用方法吗?

FontMetrics metrics = getFontMetrics( font );
int width = metrics.stringWidth( string );

PS:没有使用布局管理器。

您需要在组件上使用setPreferredSize() 然后,要调整它的大小,请调用setBounds()

我可能会继承该按钮,并覆盖setText(String text)方法以包含调整大小代码。

@Override
public void setText(String arg0) {
    super.setText(arg0);
    FontMetrics metrics = getFontMetrics(getFont()); 
    int width = metrics.stringWidth( getText() );
    int height = metrics.getHeight();
    Dimension newDimension =  new Dimension(width+40,height+10);
    setPreferredSize(newDimension);
    setBounds(new Rectangle(
                   getLocation(), getPreferredSize()));
}

为了测试,我在我的新JButton子类的构造函数中做到了这一点:

public ResizeToTextButton(String txt){
    super(txt);
    addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent arg0) {
            setText(JOptionPane.showInputDialog("Text"));
        }
    });
}

因此,每当我点击按钮时,我都可以更改文本并查看它是否正确调整大小。

即使使用布局管理器(BorderLayout),我也遇到了同样的问题。 但在我的例子中,简单地调用相关布局管理器的layoutContainer()然后在JFrame上调用repaint()就足以改变按钮的宽度。

button1.setText("New Label that differs in width");
// button1 is inside the container horizontalBox
horizontalBox.getLayout().layoutContainer(horizontalBox);
repaint(); // on the containing JFrame

暂无
暂无

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

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