automatic font resize

微笑、不失礼 提交于 2019-12-13 21:51:57

问题


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


回答1:


It is possible to compute the text width for a given font with the FontMetrics class and compare this length with the textfield width.

JtextField field = new JTextField();
FontMetrics fm = field.getFontMetrics(field.getFont());
int textwidth = fm.stringWidth(field.getText());



回答2:


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


来源:https://stackoverflow.com/questions/3646832/automatic-font-resize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!