【发布时间】:2019-06-19 06:14:53
【问题描述】:
我的申请卡住了。每次我运行我的代码时,我的字段例如fromTextField 一次宽度为 180 其他时间我的宽度 private static final Integer widthField = 232。
代码:
package gui;
import javax.swing.*;
import java.awt.*;
public class MailGui extends JFrame {
private static final Integer widthField = 232;
private MailGui() {
JPanel northPanel = new JPanel();
northPanel.setLayout(new GridLayout(5, 5));
JLabel fromLabel = new JLabel("From: ", SwingConstants.LEFT);
JLabel passwdLabel = new JLabel("Password: ", SwingConstants.LEFT);
JLabel toLabel = new JLabel("To: ", SwingConstants.LEFT);
JLabel subjectLabel = new JLabel("Subject: ", SwingConstants.LEFT);
JLabel textLabel = new JLabel("Content: ", SwingConstants.LEFT);
JTextField fromTextField = new JTextField();
JTextField toTextField = new JTextField();
JPasswordField passwdPasswordField = new JPasswordField();
JTextField subjectTextField = new JTextField();
JTextArea textArea = new JTextArea(8, 30);
JButton sendButton = new JButton("Send");
textArea.setLineWrap(true);
northPanel.add(fromLabel);
northPanel.add(fromTextField);
northPanel.add(passwdLabel);
northPanel.add(passwdPasswordField);
northPanel.add(toLabel);
northPanel.add(toTextField);
northPanel.add(subjectLabel);
northPanel.add(subjectTextField);
northPanel.add(textLabel);
northPanel.add(textArea);
this.add(northPanel, BorderLayout.NORTH);
JScrollPane scrollPane = new JScrollPane(textArea);
this.add(scrollPane, BorderLayout.CENTER);
JPanel southPanel = new JPanel();
southPanel.add(sendButton);
add(southPanel, BorderLayout.SOUTH);
this.pack();
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
this.setResizable(false);
fromTextField.setBounds(textArea.getX() + 100, 0, widthField, 19);
passwdPasswordField.setBounds(textArea.getX() + 100, 19, widthField, 19);
toTextField.setBounds(textArea.getX() + 100, 38, widthField, 19);
subjectTextField.setBounds(textArea.getX() + 100, 57, widthField, 19);
}
public static void main(String[] args) {
new MailGui();
}
}
我有什么:
或者
我除了:
感谢您的每一个帮助。问。
【问题讨论】:
-
该代码中有一些可疑且不是最佳的代码,但我运行了 6 次并得到了same result every time。
-
那是有线的……那我该怎么办呢?有什么建议吗?
-
首先: 1) 在 EDT 上启动 GUI。 2) 不要尝试为组件设置明确的尺寸或位置或位置。而是使用布局和布局填充来获得所需的效果。 3) 不要将
GridLayout用于标签和字段组合。网格布局将使所有组件具有相同的宽度。相反,可以为该部分使用GridBagLayout。 ..
标签: java swing layout layout-manager