Java GridBagLayout-GridBagConstraints不起作用
我试图使用Java GridBagLayout-GridBagConstraints不起作用,java,swing,layout-manager,gridbaglayout,Java,Swing,Layout Manager,Gridbaglayout,我试图使用GridBagLayout,但是GridBagConstraints对象没有显示任何效果。我想要一个按钮来填充水平空间。有什么想法吗 static class Five extends JFrame { public Five() { setSize(300, 400); setDefaultCloseOperation(EXIT_ON_CLOSE); setLayout(new GridBagLayout());
GridBagLayout
,但是GridBagConstraints
对象没有显示任何效果。我想要一个按钮来填充水平空间。有什么想法吗
static class Five extends JFrame {
public Five() {
setSize(300, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.HORIZONTAL;
JButton button = new JButton("Long-Named Button 4");
add(button, c);
setVisible(true);
}
这项工作,详情见评论:
import java.awt.*;
import javax.swing.*;
public class Five extends JFrame {
public Five() {
setSize(300, 400);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// best to do all important stuff in a panel added to the frame
JPanel gui = new JPanel(new GridBagLayout());
setContentPane(gui);
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 1d; // fixes the problem
JButton button = new JButton("Long-Named Button 4");
add(button, c);
pack(); // should always be done after all components are added
setVisible(true);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
new Five();
}
};
SwingUtilities.invokeLater(r);
}
}
更多提示:
JFrame
没有好的理由。在这种情况下,只需对标准框架的实例进行相关的添加等gui
面板周围添加EmptyBorder
main(..)
方法结束相关导入。2) 发布一个屏幕截图(或一个链接)的图形用户界面拉伸比自然大小更宽。如果它有助于解决问题,请。