根据文本调整JButton和其他组件的大小 [英] Resizing JButtons and other components according to text
问题描述
如何在运行时调整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屋!