如何在运行时调整 JButton 的大小,使其适应 setSize
给定的文本?我已经做了一些搜索,这是我到目前为止提出的代码。这可以变成实用方法吗?
FontMetrics metrics = getFontMetrics( font );
int width = metrics.stringWidth( string );
P.S: 没有使用布局管理器。
最佳答案
您需要在组件上使用 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"));
}
});
}
因此,每当我单击按钮时,我都可以更改文本并查看其大小是否正确调整。
关于java - 根据文本调整 JButton 和其他组件的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3485088/