在容器java的中心按钮

1 java swing containers jbutton

我有一个项目要求我创建一个简单的GUI,顶部有一个jTextArea,JButtons从0到9添加.这很简单,但程序要求我将0置于底部.下面的代码完成了,但是我必须使用Grid Layout而不是flowLayout.当我用GridLayout编写它时,除了左侧,我无法将0对齐到任何东西.如何使用GridLayout,并将0居中?

public class CalculatorProject {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    GUI gui = new GUI();
}

}

public class GUI extends JFrame {

public GUI() {
    JFrame aWindow = new JFrame("Calculator");
    aWindow.setBounds(30, 30, 175, 215); // Size
    aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JTextField jta = new JTextField(20);
    FlowLayout flow = new FlowLayout(); // Create a layout manager
    flow.setHgap(5);                   // Set the horizontal gap
    flow.setVgap(5);
    flow.setAlignment(FlowLayout.CENTER);
    Container content = aWindow.getContentPane(); // Get the content pane
    content.setLayout(new GridLayout(4,3,5,5));

    content.setLayout(flow); // Set the container layout mgr
    content.add(jta);
    // Now add six button components
    int array[] = {7, 8, 9, 4, 5, 6, 1, 2, 3, 0};
    for (int i = 0; i <= 9; i++) {
        content.add(new JButton("" + array[i])); 

    }
    aWindow.setVisible(true); // Display the window
}
}
Run Code Online (Sandbox Code Playgroud)

Cod*_*ner 6

通过使用BorderLayout就是这么简单.将TextField添加到North.现在只需将九个按钮添加到JPanel.将该JPanel添加到中心.最后将零按钮添加到南方.

public class CalculatorProject {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    GUI gui = new GUI();
                }
            });

    }

    }

    class GUI extends JFrame {

    GUI() {
        super("Calculator");
        setBounds(30, 30, 160, 190); // Size
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        JTextField jta = new JTextField(20);
        JPanel panel = new JPanel();
        setLayout(new BorderLayout(5, 5));
        Container content = this.getContentPane(); // Get the content pane
        content.add(jta, BorderLayout.NORTH);
        // Now add six button components
        int array[] = {7, 8, 9, 4, 5, 6, 1, 2, 3};
        for (int i = 0; i < 9; i++) {
            panel.add(new JButton("" + array[i])); 

        }
        content.add(panel, BorderLayout.CENTER);
        content.add(new JButton("0"), BorderLayout.SOUTH);
        setVisible(true); // Display the window
    }
    }
Run Code Online (Sandbox Code Playgroud)

结果

在此输入图像描述