Hello,
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
Hello,
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
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 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());