Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set a JTextField width in maner to wrap a given text

I have an uneditable and disabled JtextField in which I will put a String obtained after requesting a Database, and I want that this JtextField wraps All my String.

I saw the setColumn() and setSize() methods but I don't know first my String length.

thank you very much.

like image 362
RiadSaadi Avatar asked Mar 20 '23 09:03

RiadSaadi


1 Answers

  • JTextFields can only display a single line of text, period.
  • If you need a simple text component that wraps text, use a JTextArea.
  • Set its columns and rows.
  • Put it into a JScrollPane (if you feel the text will go beyond the number of rows specified).
  • Call setLineWrap(true) on it
  • Call setWrapStyleWord(true) on it.

Edit
You ask about resizing the JTextField as text is being added or removed. I suppose that you could always override a JTextField's getPreferredSize() method, and revalidate/repaint its container on any change in text, but doing so does carry risk.

For example:

import java.awt.*;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

public class VaryingTextFieldSize {
   protected static final int GAP = 5;

   public static void main(String[] args) {
      final JTextField textField = new JTextField(1) {
         @Override
         public Dimension getPreferredSize() {
            Dimension superPref = super.getPreferredSize();
            FontMetrics fontMetrics = getFontMetrics(getFont());
            String text = getText();
            if (text.length() > 0) {
               int width = fontMetrics.charsWidth(text.toCharArray(), 0, text.length()) + GAP;
               return new Dimension(width, superPref.height);
            }
            return superPref;
         }
      };
      textField.getDocument().addDocumentListener(new DocumentListener() {
         @Override
         public void removeUpdate(DocumentEvent e) {
            reSize();
         }

         @Override
         public void insertUpdate(DocumentEvent e) {
            reSize();
         }

         @Override
         public void changedUpdate(DocumentEvent e) {
            reSize();
         }

         private void reSize() {
            SwingUtilities.invokeLater(new Runnable() {
               public void run() {
                  Container container = textField.getParent();
                  container.revalidate();
                  container.repaint();
               }
            });
         }
      });
      JPanel enclosingPanel = new JPanel();
      enclosingPanel.setPreferredSize(new Dimension(300, 100));
      enclosingPanel.add(textField);
      JOptionPane.showMessageDialog(null, enclosingPanel);
   }
}
like image 193
Hovercraft Full Of Eels Avatar answered Mar 23 '23 08:03

Hovercraft Full Of Eels