作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在 JFrame 中创建一个与 JPanel 的接口(interface),其中 JPanel 的宽度设置为等于 JFrame 的宽度。与我的预期相反,当我运行程序查看显示时,JPanel 显示为一个非常小的框,小于所需的大小,其宽度应等于 JFrame 的宽度。但是,当我将 JPanel 的宽度减少大约 6 时,它在 JFrame 中显示得很好。在我看来,JFrame 可能有某种边距或填充,但我真的不知道。请帮助并说明为什么我不能使 JPanel 的宽度与父 JFrame 的宽度相同,以及如何在可能的情况下完成。我真的想让它们具有相同的宽度,因为这就是我的设计设置方式。我的代码如下:
`import java.awt.*; //importing awt package
import javax.swing.*; //importing swing package
//class definition
public class PMSysClient {
//declaration of variables
private JFrame lgFrame; //login frame
private JFrame fdFrame; //frame for front desk
private JFrame docFrame; //frame for doctor
private JPanel logHeadPan; //header panel in login
private JPanel logAreaPan; //login area panel
//constructor definition
public PMSysClient() {
initialise();
}//end of constructor
//method to initialise class
public void initialise() {
lgFrame = new JFrame();
Container cont = lgFrame.getContentPane();
lgFrame.setSize(863, 569);
lgFrame.setLocationRelativeTo(null);
lgFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
cont.setBackground(new Color(231, 228, 204));
cont.setLayout(new GridBagLayout());
logHeadPan = new JPanel();
logHeadPan.setBackground(new Color(204, 153, 255));
logHeadPan.setPreferredSize(new Dimension(863, 210));
GridBagConstraints c1 = new GridBagConstraints();
c1.weighty = 0.1;
c1.weightx=0.1;
c1.gridx = 0;
c1.gridy = 0;
c1.anchor = GridBagConstraints.FIRST_LINE_START;
lgFrame.add(logHeadPan, c1);
lgFrame.setVisible(true);
}//end of initialise
//main method definition
public static void main(String[] args) {
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
} catch (Exception e) {
}
new PMSysClient();
}//end of main method
}`
最佳答案
由于您的目标是使 JPanel
的宽度与父级 JFrame
的宽度相同,因此您可以在 GridBagConstraints< 中设置填充
到:
c1.fill = GridBagConstraints.HORIZONTAL;
虽然这会产生一个薄的水平面板,所以要使高度在 Y 轴上扩展,您也可以使用:
c1.fill = GridBagConstraints.BOTH;
最好将大小留给 Layoutmanagers 并避免为组件设置首选大小。
关于java - 当宽度与父 Jframe 相同时,jpanel 变成一个小盒子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12662934/
我是一名优秀的程序员,十分优秀!