[英]Java GridBagLayout with components inside
我正在嘗試使具有兩個面板的GridBagLayout分別占框架的40%和60%,同時能夠在其中包含組件,這很麻煩。
當我不將按鈕放在面板內時,它的工作方式與我希望的一樣。
不太確定我在做什么錯,我嘗試將按鈕的創建移到創建GridBagLayout的面板的位置,但是仍然無法正常工作。
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Test{
public void display(){
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(900,650);
frame.setVisible(true);
JPanel test = new JPanel();
test.setLayout(new GridBagLayout());
GridBagConstraints c= new GridBagConstraints();
JPanel left= new JPanel();
JPanel right= new JPanel();
c.fill = GridBagConstraints.VERTICAL - GridBagConstraints.HORIZONTAL;
c.weightx = 0.4;
c.gridx = 1;
c.weighty = 1;
test.add(left,c);
c.weightx = .6;
c.gridx = 2;
test.add(right,c);
JButton button= new JButton("A button");
left.add(button,c);//If I do not add this, then it shows how I want it to be
frame.add(test);
}
}
權重的問題在於它們描述了如何處理多余的空間。 組件具有其首選的最小和最大尺寸,布局管理器在計算布局時會使用它們的最小和最大尺寸。 然后,GridBagLayout使用這些權重分割多余的空間。 在您的情況下,我認為被分割的空間等於900-button.getPreferredSize()。width。 您正在將800像素分為320和480。
這是使用GridBagLayout創建的面板的示例:(不必擔心swing工廠,只需創建一個組件即可)
private void buildSourcePanel() {
JPanel pnlSource = new JPanel();
GridBagLayout gbl_pnlSource = new GridBagLayout();
gbl_pnlSource.columnWeights = new double[]{0.0, 0.0, 0.0, 0.0, 0.0};
gbl_pnlSource.columnWidths = new int[]{0, 0, 100, 100, 25};
pnlSource.setLayout(gbl_pnlSource);
final JLabel lblFolderMask = swingFactory.createLabel(" SOURCE DIRECTORY ", null, null, SwingConstants.LEFT, SwingConstants.CENTER, true);
pnlSource.add(lblFolderMask, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, 10, 1, new Insets(5, 5, 5, 0), 0, 0));
txtSource = swingFactory.createTextField(null, "txtSource", null, SystemColor.textHighlight, SwingConstants.LEFT, false, true, "Source Directory");
pnlSource.add(txtSource, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, 10, 1, new Insets(5, 0, 5, 5), 0, 0));
final JButton btnBrowse = new JButton("Browse...");
btnBrowse.setBorder(new CompoundBorder(new LineBorder(new Color(0, 0, 0), 0, false), new EmptyBorder(5, 5, 5, 5)));
btnBrowse.setFont(new Font("Verdana", Font.BOLD, 14));
pnlSource.add(btnBrowse, new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0, 10, 1, new Insets(5, 0, 5, 5), 0, 0));
final JButton btnClear = new JButton("Clear...");
btnClear.setBorder(new CompoundBorder(new LineBorder(new Color(0, 0, 0), 0, false), new EmptyBorder(5, 5, 5, 5)));
btnClear.setFont(new Font("Verdana", Font.BOLD, 14));
pnlSource.add(btnClear, new GridBagConstraints(3, 0, 1, 1, 0.0, 0.0, 10, 1, new Insets(5, 0, 5, 5), 0, 0));
lblStatus = swingFactory.createLabel(null, null, null, SwingConstants.CENTER, SwingConstants.CENTER, false);
pnlSource.add(lblStatus, new GridBagConstraints(4, 0, 1, 1, 0.0, 0.0, 10, 1, new Insets(5, 5, 5, 5), 0, 0));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.