【问题标题】:GribBaglayout not displaying correctlyGribBaglayout 未正确显示
【发布时间】:2014-08-31 19:15:54
【问题描述】:

我试图让我的标签和组合框靠得更近,并将我的文本区域放在框架的底部。我的组合框和标签紧挨着,但距离不对,我看不到我的文本区域。然后,当我调整框架大小时,所有内容都会显示出来,并且我的组合框和文本区域大小合适,只是间距错误。我认为这是一个重量问题,但是当我调整重量数字时,我没有得到任何改变。感谢您的帮助!

代码如下:

 //add menu items 
     menu1.add(save);
     menu1.add(close);
     menu.add(menu1);
     menu.add(menu2);
     //Creates tabbed items
     tab.addTab("Scan", null, tab1, "Start a scan!");
     tab.addTab("Timed Scan", null, tab2, "Start a timed Scan");

     //add GUI items 
     panel.setLayout(new BorderLayout());
     panel.add(menu, BorderLayout.NORTH);
     panel.add(tab);


      JButton IPscan = new JButton("IP");
     JTextArea response = new JTextArea();
     Dimension textSize = new Dimension(400,100);
     Dimension comboSize = new Dimension(100,25);
     response.setPreferredSize(textSize);

     //Tab1
     GridBagLayout gridBagLayout = new GridBagLayout();
     GridBagConstraints c = new GridBagConstraints();
    // c.weightx = .1;
     c.weighty = .5;
    tab1.setLayout(gridBagLayout);
     response.setLineWrap(true);
     response.setWrapStyleWord(true);
     response.setText("Scan results:");
     c.gridx = 0;
     c.gridy = 4;
     tab1.add(response, c);
     c.anchor = GridBagConstraints.NORTHWEST;
     c.gridx = 0;
     c.gridy = 0;
     tab1.add(choseScan, c);
     scanOp.setPreferredSize(comboSize);
     c.gridx = 1;
     tab1.add(scanOp,c);


     //tab2
     tab2.setLayout(gridBagLayout);
     c.gridx = 1;
     c.gridy = 1;
     tab2.add(scan1, c);



     frame.add(panel);
     frame.setDefaultCloseOperation(frame.EXIT_ON_CLOSE);
     Dimension d = new Dimension(500,500);
     frame.setPreferredSize(d);
     frame.pack();
     //shows everything
     frame.setVisible(true);



     return 5;
 }

【问题讨论】:

  • 尝试设置尺寸和首选尺寸可能会伤害自己。而是让组件和布局为您完成所有这些工作,否则您可以将您的 GUI 限制为不会显示的大小(这可能是您的问题)。还可以考虑创建并发布Minimal, Complete, and Verifiable Example Program,在其中将代码压缩为仍可编译和运行的最小位,没有外部依赖项,没有与您的问题无关的额外代码,但仍能证明您的问题。

标签: java swing layout-manager gridbaglayout


【解决方案1】:

我无法运行您的代码,但我立即发现一件事可能导致您的初始大小不正确。

frame.add(panel);

如果你尝试这样的事情:

frame.setLayout(new GridBagLayout());

GridBagConstraints gBC = new GridBagConstraints();
gBC.fill = GridBagConstraints.BOTH;
gBC.weightx = 1.0;
gBC.weighty = 1.0;

frame.add(panel, gBC);

在将 JTabbedPane 添加到 JPanel 时,您也需要这样做。

【讨论】:

    猜你喜欢
    • 2012-04-13
    • 1970-01-01
    • 1970-01-01
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多