自动字体大小调整 [英] automatic font resize

查看:156
本文介绍了自动字体大小调整的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何找出JTextField中的文本是否大于这些JTextField的可见区域,以便更改字体大小?

How can I find out, if a text in a JTextField is larger than visible area of these JTextField, so that I can change the font size?

感谢您的帮助. 真挚地 基督徒

Thx for any help. Sincerely Christian

推荐答案

相反,请问JTextField所选字体的高度,然后根据您的要求设置首选宽度,例如在下面的示例中为240.用户可以使用左右箭头键滚动文本.

Instead, ask the JTextField how tall it should be for a chosen font and set the preferred width to your specification, e.g. 240 in the example below. The user can use the left and right arrow keys to scroll through the text.

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;

/** @see http://stackoverflow.com/questions/3646832 */
public class JTextFieldTest extends JPanel {

    public JTextFieldTest() {
        String s = "A damsel with a dulcimer in a vision once I saw.";
        JTextField tf = new JTextField(s);
        tf.setFont(new Font("Serif", Font.PLAIN, 24));
        tf.validate();
        int h = tf.getPreferredSize().height;
        tf.setPreferredSize(new Dimension(240, h));
        tf.getCaret().setDot(0);
        this.add(tf);
    }

    private void display() {
        JFrame f = new JFrame("JTextFieldTest");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.add(this);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new JTextFieldTest().display();
            }
        });
    }
}

附录:甚至更好,使用合适的布局并相应地设置包含面板的首选大小.如果用户放大窗口,这将使您的初始布局呼吸".

Addendum: Even better, use a suitable layout and set the containing panel's preferred size accordingly. This allows your initial layout to "breathe" if the user enlarges the window.

public JTextFieldTest() {
    this.setLayout(new BoxLayout(this, BoxLayout.PAGE_AXIS));
    String s = "It was an Abyssinian maid, and on her dulcimer she played,";
    JTextField tf = new JTextField(s);
    tf.setFont(new Font("Serif", Font.PLAIN, 24));
    tf.validate();
    int h = tf.getPreferredSize().height;
    tf.getCaret().setDot(0);
    this.setPreferredSize(new Dimension(240, h));
    this.add(tf);
}

这篇关于自动字体大小调整的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆