【发布时间】:2014-01-11 04:31:08
【问题描述】:
当我最大化或重新调整JFrame 的大小时,我希望我的JPanel 仍位于中心。我该怎么做?
试过了:
jframe.add(panel, BorderLayout.CENTER);
panel.setAlignmentX(JComponent.CENTER_ALIGNMENT);
但它不起作用。
这是我的其他代码:
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
login frame = new login();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public login() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setBounds(5, 5, 409, 267);
setLocationRelativeTo(null);
contentPane = new JPanel();
contentPane.setBackground(new Color(0, 128, 128));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
panel = new JPanel();
panel.setBounds(57, 42, 292, 167);
panel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Login", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 255)));
panel.setLayout(null);
contentPane.add(panel);
textField = new JTextField();
textField.setBounds(71, 35, 192, 26);
panel.add(textField);
textField.setColumns(10);
passwordField = new JPasswordField();
passwordField.setBounds(71, 72, 192, 26);
panel.add(passwordField);
JLabel lblNewLabel = new JLabel("Username:");
lblNewLabel.setBounds(6, 41, 68, 14);
panel.add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("Password:");
lblNewLabel_1.setBounds(6, 78, 68, 14);
panel.add(lblNewLabel_1);
JButton btnNewButton = new JButton("Login");
btnNewButton.setBounds(71, 120, 89, 23);
panel.add(btnNewButton);
JButton btnNewButton_1 = new JButton("Cancel");
btnNewButton_1.setBounds(174, 120, 89, 23);
panel.add(btnNewButton_1);
我该怎么做呢?
【问题讨论】:
-
1) Java GUI 可能必须在多个平台、不同的屏幕分辨率和使用不同的 PLAF 上工作。因此,它们不利于组件的精确放置。要为强大的 GUI 组织组件,请改用布局管理器或 combinations of them,以及 white space 的布局填充和边框。 2) 为了尽快获得更好的帮助,请发布MCVE(要成为 MCVE,该代码需要类声明和导入)。