簡體   English   中英

根據文本調整JButton和其他組件的大小

[英]Resizing JButtons and other components according to text

如何在運行時調整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()然后在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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM