增加 JTextField 组件的高度

Increase height of the JTextField component

我正在使用 Java Swing 创建一个计算器。但是我无法增加 JTextField 组件的高度。请在下面找到代码:

JTextField textField = new JTextField(100);
JPanel mainPanel = new JPanel(new BorderLayout());
mainPanel.add(textField, BorderLayout.PAGE_START);

文本域显得很小。如何增加文本框的高度以使其更加突出?

谢谢

我认为最好让文本字段根据使用的字体确定高度。

String str = "21564";
JTextField textField = new JTextField(str, 100);
Font bigFont = textField.getFont().deriveFont(Font.PLAIN, 150f);
textField.setFont(bigFont);
mainPanel.add(textField);

Swing Tutorial

有很多方法可以实现。首先,是 use a proper Layout Manager. It is always recommended not to mess with a bunch of hardcoded values and let APIs to do what they supposed to do. However, without a short self contained example 很难猜出你知道和使用什么,不知道什么。

所以我想另一种方法是为组件(或其相应的父容器)创建一个空边框。不过在 JTextField 中,您可能希望保留默认边框,因此您将不得不使用复合边框:

JTextField field = new JTextField(20);
Border outsideBorder = field.getBorder();
Border insideBorder = BorderFactory.createEmptyBorder(10, 0, 10, 0); //insets
field.setBorder(BorderFactory.createCompoundBorder(outsideBorder, insideBorder));
frame.add(field);