Search code examples
javaswinguser-interfacejtextfieldjtoolbar

Add JTextField to JToolBar


I'm trying to add JTextField to JToolBar and it works, but it is too long. I need it to take only 3 letters.

Here is the screenshot of it now... screenshot

I tried following methods,

JTextField field = new JextField(3); // thought this limits to three characters.

And I tried,

field.setColumns(3); // this didn't work either.

Solution

  • The default layout of a tool-bar respects the maximum size set for a text field.

    Text Field in Tool Bar

    import java.awt.*;
    import javax.swing.*;
    
    public class TextFieldInToolBar {
    
        TextFieldInToolBar() {
            JPanel p = new JPanel(new BorderLayout());
    
            JToolBar tb = new JToolBar();
            p.add(tb, BorderLayout.PAGE_START);
    
            Icon disk = (Icon)UIManager.get("FileView.floppyDriveIcon"); 
            Icon pc = (Icon)UIManager.get("FileView.computerIcon"); 
            tb.add(new JButton(disk));
            JTextField tf = new JTextField(3);
            tf.setMaximumSize(tf.getPreferredSize());
            tb.add(tf);
            tb.addSeparator();
            tb.add(new JButton(pc));
    
            p.setPreferredSize(new Dimension(250,50));
    
            JOptionPane.showMessageDialog(null, p);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    new TextFieldInToolBar();
                }
            });
        }
    }