我在使用GridBagLayout時遇到了問題,一切似乎都按預期工作,但JFrame的底部有一個小缺口,我似乎無法擺脫。Java - JFrame底部的額外像素(GridBagLayout)
這是我運行的代碼......
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Test {
private JFrame frame;
private JPanel container, header, content, footer;
public Test(){
frame = new JFrame();
frame.setSize(600, 400);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridBagConstraints gbc = new GridBagConstraints();
container = new JPanel();
container.setBackground(Color.blue);
container.setLayout(new GridBagLayout());
header = new JPanel();
header.setBackground(Color.red);
header.setLayout(new FlowLayout(FlowLayout.LEFT,0,0));
header.add(new JButton("Test"));
gbc.gridx = 0;
gbc.gridy = 0;
gbc.weightx = 1.0;
gbc.fill = GridBagConstraints.BOTH;
container.add(header, gbc);
content = new JPanel();
content.setBackground(Color.green);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.weightx = 1.0;
gbc.weighty = 0.9;
gbc.fill = GridBagConstraints.BOTH;
container.add(content, gbc);
footer = new JPanel();
footer.setBackground(Color.gray);
gbc.gridx = 0;
gbc.gridy = 2;
gbc.weightx = 1.0;
gbc.weighty = 0.1;
gbc.fill = GridBagConstraints.BOTH;
container.add(footer, gbc);
frame.getContentPane().add(container);
frame.setMinimumSize(new Dimension(600,400));
}
public static void main(String[] args) {
Test main = new Test();
main.frame.pack();
main.frame.setVisible(true);
}
}
你會發現還有約2-3個像素仍呈現在用戶界面的底部,對於容器背景當然是藍色的。即使調整大小,這種差距仍然存在。我猜測它與GridBagConstraint權重有關,因爲當我嘗試將weightY設置爲相等的值時,問題會自行解決,但這顯然不是我想要的樣子。
這實際上是一個'GridBagLayout'(由於某種原因超過16年我從來沒有親自有過)的一個已知問題,但基本上,它歸結爲如何'GridBagLayout'計算剩餘空間和舍入差異,顯然 – MadProgrammer
計算的標準問題(例如10/3 = 3 x 3,此處保留1像素),可以在父容器的擴展期間模擬,也可以通過測試SpringLayout來看到它 – mKorbel
發佈適當的[SSCCE](http://當您提出問題時,人們可以選擇測試代碼。你的代碼應該包含類和變量。 – camickr