Search code examples
javaswingjtextfield

How can I scale font size to automatically accommodate a static JTextField size?


I'm making a Matrix calculator in Java using a two-dimensional array of JTextFields on a JPanel to input a given Matrix. Since the panel that this matrix is placed on has a fixed size, I want to scale down the text size to accommodate how long the number is as it's being typed in.

For example: If it's one digit long, font size = 18. If it's two digits long, font size = 14. Etc. I want this to dynamically occur as the user is entering the text, and I want repainting to occur everytime the user interacts with the JTextField, not only after the user presses "enter". This is because the field is transparent and currently looks sloppy (numbers overlapping) until the user presses enter.

What's the most straightforward and reliable way to do this? Here's my current code if it helps anyone answer my question:

public class MatrixPanel extends JPanel implements ActionListener
{
  float[][] matrice = new float[3][3];
  JTextField[][] parameter = new JTextField[3][3];
  Font font = new Font("SansSerif", Font.BOLD, 40);


public MatrixPanel(String title)
{
  setLayout(null);
  setOpaque(false);

for (int width = 0; width < 3; width++){
  for (int height = 0; height < 3; height++){
    matrice[width][height] = 0;
    parameter[width][height] = new JTextField();
    parameter[width][height].setHorizontalAlignment(JTextField.CENTER);
    parameter[width][height].setFont(font);
    parameter[width][height].setText("0");
    parameter[width][height].setLocation((50*width), (50*height));
    parameter[width][height].setSize(50,50);
    parameter[width][height].setOpaque(false);
    parameter[width][height].setBorder(null);
    parameter[width][height].addActionListener(this);
    add(parameter[width][height]);
  }

setSize(150,150);
 }
}

Solution

  • I want to scale down the text size to accommodate how long the number is as it's being typed in.

    Take a look to How to Write a DocumentListener to achieve your goal.

    Some useful tips: