Java使用GridLayout创建一种表单?

Sha*_*lam 1 java swing layout-manager grid-layout

我正在尝试制作毕达哥拉斯定理计算器.现在,我正在尝试使用表单GridLayout.输入A,B或C侧的值,然后选中缺失侧的单选按钮.但是,我JTextField太大了,我希望它能与标签保持一致.我不想使用任何其他lyout经理.

import java.awt.*;
import javax.swing.JFrame;
import javax.swing.*;

public class TriangleCalculator extends JFrame{

    private JLabel sideALabel, sideBLabel, sideCLabel, triangleImage;
    private JTextField sideAInput,sideBInput, sideCInput;
    private JRadioButton sideAOption, sideBOption, sideCOption;
    private JButton calculateButton, clearButton;
    private JPanel buttonPane, mainPanel;

    public TriangleCalculator(){
        super("TriangleCalculator");
        addComponents();
        setSize(500, 500);
        setVisible(true);

    }

    public void addComponents()
    {
        sideALabel = new JLabel("Enter the value of side A: ");
        sideBLabel = new JLabel("Enter the value of side B: ");
        sideCLabel = new JLabel("Enter the value of side C: ");

        sideAInput = new JTextField();
        sideBInput = new JTextField();
        sideCInput = new JTextField();

        sideAOption = new JRadioButton();
        sideBOption = new JRadioButton();
        sideCOption = new JRadioButton();

        calculateButton = new JButton("Calculate");
        clearButton = new JButton("Clear");

        buttonPane = new JPanel(new GridLayout(0, 2));
        mainPanel = new JPanel(new GridLayout(0, 3));
        add(buttonPane, BorderLayout.SOUTH);
        add(mainPanel, BorderLayout.CENTER);

        mainPanel.add(sideALabel);
        mainPanel.add(sideAInput);
        /*mainPanel.add(sideAOption);*/

        buttonPane.add(clearButton);
        buttonPane.add(calculateButton);
    }
}
Run Code Online (Sandbox Code Playgroud)

cam*_*ckr 5

我不想使用任何其他lyout经理.

这不是布局管理的工作方式.每个布局管理器都有其规则.如果一个布局管理器没有执行您想要的操作,那么您需要使用不同的布局管理器或包含不同布局管理器的嵌套面板来实现您的效果.

你可以用一个GridBagLayout.它将支持不同大小的列.但是,在创建文本字段时,您需要使用:

sideAInput = new JTextField(10);
Run Code Online (Sandbox Code Playgroud)

所以布局管理器知道创建文本字段有多大.

阅读Swing教程中有关如何使用GridBagLayout的部分,获取更多信息和工作示例.