5

JButton テキストのフォント サイズを自動的に拡大/縮小しようとしています (JButton が拡大/拡大するとテキストも拡大し、JButton が縮小するとテキストも縮小します)。JButton のデフォルトのフォントは Sans-Serif サイズ 20 であり、20 未満になることはありません (21、30、40、または 20 以上のいずれかになりますが、20 未満になることはありません)。私は MenuJPanel と呼ばれる JPanel を持っています。それは GridLayout を使用して、JPanel が増加/減少するにつれてサイズが増加/減少する 5 つの JButton を追加します。この目的に最適なレイアウトと思われる GridLayout を選択しましたが、間違っていますか? また、ComponentResized を MenuJPanel に追加しました。以下に、部分的に機能する私のコードを示します。

ここに画像の説明を入力

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);
    }
}
4

1 に答える 1

5

通常、デザイナーが選択したフォントとプラットフォームの美学に基づいて、ボタンの優先サイズを計算するButtonUIためのデリゲートが計算されます。JButtonあなたのアプローチがこれを打ち負かすと、テキストがボタンでどのようにスケーリングされ、ボタンの装飾に対応するかを決定するのはあなた次第です。

独自の を作成しButtonUIなくても、テキストを単純にスケーリングできます。このでは、 を使用して、必要に応じて縮小できる任意の大きなサイズでTextLayoutテキストをレンダリングします。BufferedImageこのでは、1 桁のグリフが にレンダリングされBufferedImage、ボタンの現在のサイズに合わせてスケーリングされます。の相対位置を処理する必要がある場合はIcon、 を参照SwingUtilities.layoutCompoundLabel()てください

于 2012-12-05T19:17:57.930 に答える