Abh*_*nai 1 java swing jtextfield layout-manager grid-layout
我有一个文本字段,如电子邮件地址、城市和地址,
我想让地址文本字段应该更大,如图所示!
我使用 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);
Run Code Online (Sandbox Code Playgroud)
而不是使用 JTextField,使用 a JTextArea,它旨在处理多行文本。
看 更多详细信息,如何使用文本区域。
在任何情况下,您都应该提供columns(并且在JTextArea)rows值。API 有一种机制,可以根据当前的字体属性“猜测”满足这些要求所需的空间量。
这允许 API 向布局管理器 API 提供大小调整提示,然后它可以使用它来确定如何最好地定位/调整组件的大小。
要允许文本区域跨越多列,我建议您使用 GridBagLayout
请参阅如何使用 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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11291 次 |
| 最近记录: |