根据文本调整JButton和其他组件的大小 [英] Resizing JButtons and other components according to text

查看:44
本文介绍了根据文本调整JButton和其他组件的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在运行时调整JButton的大小,使其适应setSize给定的文本?我已经进行了一些搜索,这是我到目前为止提出的代码.可以将其转换为实用方法吗?

How do you resize a JButton at runtime so it adapts to the text given by setSize? I've done some searching and this is the code I've come up with so far. Could this be turned into a utility method?

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

P.S:未使用布局管理器.

P.S: No layout manager is being used.

推荐答案

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

You need to use setPreferredSize() on the component. Then, to resize it, call setBounds().

我可能会继承按钮的子类,并覆盖setText(String text)方法以包括调整大小的代码.

I would probably subclass the button, and override the setText(String text) method to include the resizing code.

@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子类的构造函数中进行了此操作:


For testing, I did this in the constructor of my new JButton subclass:

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

因此,每当我单击按钮时,我都可以更改文本并查看其大小是否正确.

So, whenever I clicked on the button I could change the text and see if it resized properly.

这篇关于根据文本调整JButton和其他组件的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆