java - 容器java上的中心按钮

标签 java swing jbutton containers

我有一个项目需要我创建一个简单的 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
}
}

最佳答案

通过使用 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
    }
    }

结果

enter image description here

关于java - 容器java上的中心按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32803856/

相关文章:

java - JButton 的可互换 JComponent 外观

java - 界面。为什么在这种情况下有用

java - 在java中,我将如何进行计算,最大的数字减去较小的数字?

java - 从通用抽象类java返回子类

swing - 如果我开始使用 Netbeans GUI 构建器制作 swing 应用程序可以吗?

java - Java中的JButton悬停效果延迟

Java - 为什么我的按钮没有显示在面板中?

java - SQL问题,Java中的ResultSet

java - JPanels 不出现在 JFame 中

java - 将 Outlook 电子邮件和其他文件拖放到 Java 应用程序