Applet 面板、一种固定尺寸和动态 JTextField
我需要一个包含一个面板的小程序。面板需要为 550x400 像素,JTextField 需要低于面板动态大小。我希望它是这样的: [顶部面板] [textPanel]
但是我正在尝试这个,看起来面板填满了所有空间。代码:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JApplet;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Client extends JApplet
{
@Override
public void init()
{
try {
java.awt.EventQueue.invokeAndWait(new Runnable()
{
public void run()
{
initComponents();
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
}
private void initComponents()
{
JPanel topPanel = new javax.swing.JPanel();
topPanel.setBackground(Color.red);
topPanel.setSize(550, 400);
topPanel.setPreferredSize(new Dimension(550, 400));
topPanel.setMinimumSize(new Dimension(550, 400));
topPanel.setMaximumSize(new Dimension(550, 400));
JTextField myTextBox = new JTextField(255);
getContentPane().add(topPanel, java.awt.BorderLayout.NORTH);
getContentPane().add(myTextBox, java.awt.BorderLayout.SOUTH);
}
// TODO overwrite start(), stop() and destroy() methods
}
谢谢!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当我测试上面的代码时,这些组件似乎处于正确的位置。我唯一注意到的是初始视口尺寸小于 550x400。由于 JPanel 的大小始终为 550x400,因此这会导致显示 JTextField 时出现一些问题。
The components seemed to be in the correct positions when I tested the above code. The only thing I noticed was that the initial view-port size was smaller than 550x400. This caused some artifacts in displaying the JTextField since the size of the JPanel is invariably 550x400.
JPanel 似乎是正确的(使用 setPreferredSize,添加到 NORTH)假设您的小程序宽度为 550,高度至少为 400。由于 BorderLayout 拉伸其组件的方式,我可能会尝试将文本字段移动到 CENTER 而不是 SOUTH。根据 Javadoc:
因此,将文本字段放在中间应该可以使其垂直拉伸,从而使其能够占用小程序的其余可用空间。
The JPanel seems correct (using setPreferredSize, adding to NORTH) assuming the your applet is 550 wide and at least 400 high. I might try moving the text field to CENTER instead of SOUTH because of how BorderLayout stretches its components. According to the Javadocs:
So putting the text field into the center should give it the vertical stretch you are looking for to enable it to take up the rest of the applet's available space.