关于Java:如何根据JButton的大小自动增加或减少JButton文本的大小?

How to automatically increase or decease size of JButton text based on the size of JButton?

我正在尝试自动增加/减小JButton文本的字体大小(如果JButton增加/伸展,其文本也会增加,如果JButton减少,其文本也会减少)。 JButton的默认字体将为Sans-Serif大小20,并且永远不会减小到20以下(它可以是21、30、40或大于或等于20的任何值,但不能小于20的任何东西)。我有一个名为MenuJPanel的JPanel,它使用GridLayout添加5个JButton,这些JButton的大小将随着JPanel的增加/减少而增加/减小。我选择了GridLayout,因为它似乎是用于此目的的最佳布局,对吗?我还向MenuJPanel添加了componentResized。在下面,您可以看到部分起作用的代码。

enter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
public class MenuJPanel extends JPanel {

    private JButton resizeBtn1;
    private JButton resizeBtn2;
    private JButton resizeBtn3;
    private JButton resizeBtn4;
    private JButton resizeBtn5;

    public MenuJPanel() {
        initComponents();
      this.addComponentListener(new ComponentAdapter() {
            @Override
            public void componentResized(ComponentEvent e) {

                Font btnFont = resizeBtn1.getFont();
                String btnText = resizeBtn1.getText();

                int stringWidth = resizeBtn1.getFontMetrics(btnFont).stringWidth(btnText);
                int componentWidth = resizeBtn1.getWidth();

                // Find out how much the font can grow in width.
                double widthRatio = (double) componentWidth / (double) stringWidth;

                int newFontSize = (int) (btnFont.getSize() * widthRatio);
                int componentHeight = resizeBtn1.getHeight();

                // Pick a new font size so it will not be larger than the height of label.
                int fontSizeToUse = Math.min(newFontSize, componentHeight);

                // Set the label's font size to the newly determined size.
                resizeBtn1.setFont(new Font(btnFont.getName(), Font.BOLD, fontSizeToUse));
            }
        });
    }

    private void initComponents() {

        resizeBtn1 = new javax.swing.JButton();
        resizeBtn2 = new javax.swing.JButton();
        resizeBtn3 = new javax.swing.JButton();
        resizeBtn4 = new javax.swing.JButton();
        resizeBtn5 = new javax.swing.JButton();

        setLayout(new java.awt.GridLayout(5, 0));

        resizeBtn1.setText("Text to resize 1");
        add(resizeBtn1);

        resizeBtn2.setText("Text to resize 2");
        add(resizeBtn2);

        resizeBtn3.setText("Text to resize 3");
        add(resizeBtn3);

        resizeBtn4.setText("Text to resize 4");
        add(resizeBtn4);

        resizeBtn5.setText("Text to resize 5");
        add(resizeBtn5);
    }
}


通常,JButtonButtonUI委托根据设计人员选择的字体和平台的美观度来计算按钮的首选大小。当您的方法无法解决此问题时,由您决定文本如何通过按钮缩放并容纳按钮装饰。

如果没有创建自己的ButtonUI,则只需缩放文本即可。在此示例中,TextLayout用于以任意大的尺寸呈现BufferedImage中的文本,可以根据需要将其按比例缩小。在此示例中,单个数字的字形以BufferedImage呈现并缩放以适合按钮的当前大小。如果需要处理Icon的相对位置,请参见SwingUtilities.layoutCompoundLabel()(在此处进行了检查)。