我有一个文本字段,例如电子邮件 ID、城市和地址,
我想让地址文本字段应该更大,如图所示!
我使用 BorderLayout 作为默认值,并使用 GridLayout 作为所选面板
top.setLayout(new GridLayout(8,4,10,10));
top.add(emailid);
top.add(temailid);
top.add(address);
top.add(taddress);
add(top, BorderLayout.CENTER);
最佳答案
不要使用 JTextField
,而是使用 JTextArea
,它旨在处理多行文本。
参见How to use text areas了解更多详情。
无论如何,您都应该提供列
(对于JTextArea
)行
值。 API 有一种机制,可以根据当前字体属性“猜测”满足这些要求所需的空间量。
这允许 API 向布局管理器 API 提供大小调整提示,然后它可以使用该提示来确定如何最好地定位/调整组件的大小。
要允许文本区域跨越多列,我建议您使用 GridBagLayout
参见How to use GridBagLayout了解更多详情
虽然有许多布局管理器,但 GridBagLayout
可能是核心 API 中最灵活的布局管理器(MigLayout 也是另一个考虑因素)。这为您提供了最大程度的控制权,您可以确定每个组件的位置和大小。
例如...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class Test1 {
public static void main(String[] args) {
new Test1();
}
public Test1() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextField email;
private JTextField city;
private JTextArea address;
public TestPane() {
email = new JTextField(10);
city = new JTextField(10);
address = new JTextArea(5, 20);
setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.insets = new Insets(4, 4, 4, 4);
gbc.anchor = GridBagConstraints.WEST;
add(new JLabel("Email ID:"), gbc);
gbc.gridx++;
add(email, gbc);
gbc.gridx++;
add(new JLabel("City:"), gbc);
gbc.gridx++;
add(city, gbc);
gbc.gridx = 0;
gbc.gridy++;
gbc.anchor = GridBagConstraints.NORTHWEST;
add(new JLabel("Address:"), gbc);
gbc.gridx++;
gbc.gridwidth = 3;
gbc.fill = GridBagConstraints.HORIZONTAL;
add(new JScrollPane(address), gbc);
}
}
}
关于java - 如何在java中使我的文本字段更大以适应GUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25513711/