有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用GridBagLayout创建3个高度可变的JPanel,一个接一个

我想用java编写一个简单的文本编辑器

我组织了我的布局,并得出结论,我基本上需要3个JPanel,一个在另一个之上。第一个和第二个将是非常短的高度,因为它们将是menubar和一个JPanel,分别包含2个JLabel。 中间的一个必须是高度最大的一个,因为所有文本都将包含在其中

我想我需要使用GridBagLayout,但这不起作用,我需要他们占据大的10倍于小的。所有这些都将利用JFrame提供的宽度

到目前为止,代码片段是-

GridBagConstraints gbc = new GridBagConstraints
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridx = 0;
gbc.gridy = 0;
mainFrame.add(upperGrid, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.gridheight = 10;
mainFrame.add(upperGrid, gbc);
gbc.gridx = 0;
gbc.gridy = 11;
mainFrame.add(upperGrid, GBC);

我得到的结果是-

Distorted GridBagLayout


共 (1) 个答案

  1. # 1 楼答案

    我建议你放弃网格布局的想法。我会做以下几点:

    1. 使用JMenuBar作为菜单栏(https://docs.oracle.com/javase/tutorial/uiswing/components/menu.html

    2. 使用边框布局:

      JFrame frame = new JFrame();
      JPanel topPanel = new JPanel();
      topPanel.setLayout(new FlowLayout());
      topPanel.add(new JLabel("Label 1"));
      topPanel.add(new JLabel("Label 2"));
      frame.add(topPanel, BorderLayout.NORTH);
      JPanel bigPanel = new JPanel();
      frame.add(bigPanel, BorderLayout.CENTER);
      

    例如,当需要安排包含大量文本字段的对话框时,可以使用GridLayout。但对于这种“粗糙”的东西,边界布局更好,也因为它可能更快。(可能,我不确定)

    编辑:如果必须使用GridBagLayout,则可以执行以下操作:

    JPanel panel = new JPanel();
    GridBagLayout layout = new GridBagLayout();
    layout.columnWidths = new int[] { 0, 0 };
    layout.rowHeights = new int[] { 0, 0, 0, 0 };
    layout.columnWeights = new double[] { 1.0, Double.MIN_VALUE };
    layout.rowWeights = new double[] { 0.0, 0.0, 1.0, Double.MIN_VALUE };
    panel.setLayout(layout);
    
    JPanel menuBar = new JPanel();
    GridBagConstraints contraints = new GridBagConstraints();
    contraints.fill = GridBagConstraints.BOTH;
    contraints.gridx = 0;
    contraints.gridy = 0;
    panel.add(menuBar, contraints);
    
    JPanel panelForLabels = new JPanel();
    contraints = new GridBagConstraints();
    contraints.fill = GridBagConstraints.BOTH;
    contraints.gridx = 0;
    contraints.gridy = 1;
    panel.add(panelForLabels, contraints);
    
    JPanel bigPanel = new JPanel();
    contraints = new GridBagConstraints();
    contraints.fill = GridBagConstraints.BOTH;
    contraints.gridx = 0;
    contraints.gridy = 2;
    panel.add(bigPanel, contraints);