有 Java 编程相关的问题?

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

java JTextField未按预期填充列?

学习使用布局。我试图制作一个非常简单的表单,它有两列,一个标签,一个文本输入,重复,直到底部的submit按钮应该跨越两列。然而,它似乎并没有像预期的那样工作。文本字段没有展开,按钮也没有展开。看起来像这样 enter image description here

这是我的密码-

package com.mypackage;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import net.miginfocom.swing.MigLayout;

public class DiceOddCalculator extends JFrame {
    public DiceOddCalculator(String title) {
        this.setSize(500, 500);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
        this.setTitle(title);

        //Layout and panel to house components
        MigLayout layout = new MigLayout("wrap 2, debug");
        JPanel panel = new JPanel(layout);

        //Components
        JLabel maxDiceLabel = new JLabel("Max value of die");
        JTextField maxDiceInput = new JTextField();
        JLabel protectionCriteriaLabel = new JLabel("Die protection Criteria:");
        JTextField protectionCriteriaInput = new JTextField("");
        JLabel numOfDiceLabel = new JLabel("Number of dice:");
        JTextField numOfDiceInput = new JTextField("");
        JButton addDice = new JButton("Add dice");

        //add to panel
        panel.add(maxDiceLabel);
        panel.add(maxDiceInput);
        panel.add(protectionCriteriaLabel);
        panel.add(protectionCriteriaInput);
        panel.add(numOfDiceLabel);
        panel.add(numOfDiceInput);
        panel.add(addDice, "span");

        //Turn window on
        this.setContentPane(panel);
        this.setVisible(true);
    }

    public static void main(String[] args) {
        DiceOddCalculator f = new DiceOddCalculator("Dice Odds Simulator");
    }
}

为了使JTextField和Button具有适当的宽度,我的代码中需要更改哪些内容


共 (1) 个答案

  1. # 1 楼答案

    我发现这与我如何构建布局有关。使用 MigLayout layout = new MigLayout("wrap 2, debug", "[fill, grow]", "")使组件像我所期望的那样在其列上拉伸