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

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

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

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

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

我可能会inheritance该按钮,并覆盖setText(String text)方法以包含resize代码。

 @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")); } }); } 

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

即使使用布局管理器(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