0

我正在尝试添加JTextFieldJToolBar并且它可以工作,但是它太长了。我需要它只取 3 个字母。

这是它现在的屏幕截图...... 截屏

我尝试了以下方法,

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

我试过了,

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

2 回答 2

3

工具栏的默认布局遵循为文本字段设置的最大大小。

工具栏中的文本字段

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();
            }
        });
    }
}
于 2012-06-05T19:39:53.607 回答
1
于 2012-06-05T19:11:57.320 回答