【发布时间】:2014-08-12 04:14:56
【问题描述】:
我正在尝试创建一个简单的电子邮件客户端,并且正文的底部正在被切断。如果我添加一个水平滚动条,它不会出现,垂直滚动条的底部也不会出现。
这是我的代码:
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
@SuppressWarnings("serial")
public class gui extends JFrame{
gui(String title, int x, int y){
super(title);
setSize(x,y);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setResizable(false);
}
public void addElements(){
Font size30 = new Font(null, Font.PLAIN, 30);
JPanel pnl = new JPanel();
Container contentPane = getContentPane();
//--- User Info ---//
JPanel userInfo = new JPanel();
JLabel userLabel = new JLabel("Username: ");
JTextField userField = new JTextField(12);
userInfo.add(userLabel);
userInfo.add(userField);
JLabel passLabel = new JLabel("Password: ");
JTextField passField = new JTextField(10);
userInfo.add(passLabel);
userInfo.add(passField);
JLabel serverLabel = new JLabel("Mail Server: ");
JTextField serverField = new JTextField(10);
userInfo.add(serverLabel);
userInfo.add(serverField);
JLabel portLabel = new JLabel("Server Port: ");
JTextField portField = new JTextField(3);
userInfo.add(portLabel);
userInfo.add(portField);
//--- To: CC: and Subject Fields ---//
JPanel msgInfo = new JPanel();
JLabel toLabel = new JLabel("To: ");
JTextField toField = new JTextField(30);
msgInfo.add(toLabel);
msgInfo.add(toField);
JLabel subLabel = new JLabel("Subject: ");
JTextField subField = new JTextField(30);
msgInfo.add(subLabel);
msgInfo.add(subField);
//--- Body ---//
JPanel bodyPnl = new JPanel(new BorderLayout(10,10));
JLabel bodyLabel = new JLabel("Body");
bodyLabel.setFont(size30);
JTextArea bodyField = new JTextArea(30,70);
bodyField.setLineWrap(true);
bodyField.setWrapStyleWord(true);
JScrollPane bodyScroll = new JScrollPane(bodyField);
bodyScroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
bodyScroll.setBounds(getX(), getY(), bodyField.getWidth(), bodyField.getHeight());
bodyPnl.add("South",bodyScroll);
pnl.add(userInfo);
pnl.add(msgInfo);
pnl.add(bodyLabel);
pnl.add(bodyScroll);
contentPane.add("North", pnl);
setVisible(true);
}
}
在我的主类中,我只是创建一个新的 gui,然后调用 addElements() 函数。
【问题讨论】:
-
pnl使用的是FlowLayout,它不能很好地“包装”,我会考虑使用不同的布局管理器 -
您的滚动条未显示,因为您的文本区域为空并且您的滚动条设置为“根据需要”。尝试使用
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS -
@error 那不是问题,问题是滚动条的底部被截断了。底部没有箭头可以让滚动条慢慢下降
-
啊,我明白了。就像 MadProgrammer 所说,这可能是由于布局管理器。这也可能是由于将 JScrollPane 设置为 JTextArea 的高度。当您将 Component 传递给 JScrollPanes 构造函数时,它应该自动补偿大小。不要设置边界 (x, y, width, height) 尝试设置 JScrollPane 的位置 (x, y)。
-
还有
pack()框架(添加组件后),而不是setSize()
标签: java swing user-interface jscrollpane jtextarea