如何在运行时调整 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()
关联的布局管理器然后repaint()
在 JFrame 上就足以改变按钮的宽度。
button1.setText("New Label that differs in width");
// button1 is inside the container horizontalBox
horizontalBox.getLayout().layoutContainer(horizontalBox);
repaint(); // on the containing JFrame