【问题标题】:Center buttons on a container java容器java上的中心按钮
【发布时间】:2015-09-27 02:08:37
【问题描述】:

我有一个项目需要我创建一个简单的 GUI,该 GUI 在顶部有一个 jTextArea,并添加了从 0 到 9 的 JButton。这很简单,但是程序要求我将 0 放在底部的中心.下面的代码实现了这一点,但是我必须使用网格布局而不是 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?这很简单。
  • @CodeRunner:他需要一个使用 BorderLayout 的 JPanel,并在其中嵌套一个 GridLayout JPanel。
  • 好的。也请查看我的答案。它可能会对你有所帮助。

标签: java swing jbutton containers


【解决方案1】:

使用 BorderLayout 就这么简单。将 TextField 添加到北方。现在只需将九个按钮添加到 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
    }
    }

结果

【讨论】:

    【解决方案2】:

    将一个空的 JPanel 添加到您希望为空的网格的正方形中。

    int array[] = {7, 8, 9, 4, 5, 6, 1, 2, 3, 0};
    for (int i = 0; i <= 8; i++) {
        content.add(new JButton("" + array[i])); 
    }
    content.add(new JPanel());
    content.add(new JButton("" + array[9]));
    content.add(new JPanel());  // not needed, but fills the last square of the grid
    

    编辑:删除了一个额外的意外出现的单词“empty”。

    【讨论】:

      【解决方案3】:

      让布局和一个简单的二维字符串数组帮助您。例如,如果您为按钮文本声明一个二维字符串数组,如下所示:

          private static final String[][] TEXTS = {
              {"7", "8", "9"},
              {"4", "5", "6"},
              {"1", "2", "3"},
              {"", "0", ""}
          };
      

      然后循环遍历数组,在文本不是"" 为空的地方创建按钮,并在其为空的地方创建一个空的 JLabel,然后使用 JPanel 将按钮放入 GridLayout,你就在那里。我还建议嵌套 JPanel,外部使用 BorderLayout,将 JTextField 放在顶部 - BorderLayout.PAGE_START,另一个 JPanel 使用 GridLayout,按住按钮并使用 JPanel 放置在外部 BorderLayout 的 BorderLayout.CENTER 位置。例如:

      import java.awt.BorderLayout;
      import java.awt.GridLayout;
      import java.util.ArrayList;
      import java.util.List;
      import javax.swing.*;
      
      public class Gui2 extends JPanel {
          private static final String[][] TEXTS = {
              {"7", "8", "9"},
              {"4", "5", "6"},
              {"1", "2", "3"},
              {"", "0", ""}
          };
          private List<JButton> buttons = new ArrayList<>();
          private JTextField textField = new JTextField(5);
      
          public Gui2() {
              int rows = TEXTS.length;
              int cols = TEXTS[0].length;
              int gap = 2;
              JPanel gridPanel = new JPanel(new GridLayout(rows, cols, gap, gap));
              for (int r = 0; r < TEXTS.length; r++) {
                  for (int c = 0; c < TEXTS[r].length; c++) {
                      String text = TEXTS[r][c];
                      if (!text.trim().isEmpty()) {
                          JButton button = new JButton(text);
                          gridPanel.add(button);
                          buttons.add(button);
                          // add ActionListener here
                      } else {
                          // empty String, so add a blank place-holder JLabel
                          gridPanel.add(new JLabel());
                      }
                  }
              }
      
              setBorder(BorderFactory.createEmptyBorder(gap, gap, gap, gap));
              setLayout(new BorderLayout(gap, gap));
              add(textField, BorderLayout.PAGE_START);
              add(gridPanel, BorderLayout.CENTER);
          }
      
          private static void createAndShowGui() {
              Gui2 mainPanel = new Gui2();
      
              JFrame frame = new JFrame("Gui2");
              frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
              frame.getContentPane().add(mainPanel);
              frame.pack();
              frame.setLocationByPlatform(true);
              frame.setVisible(true);
          }
      
          public static void main(String[] args) {
              SwingUtilities.invokeLater(new Runnable() {
                  public void run() {
                      createAndShowGui();
                  }
              });
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2011-12-31
        • 1970-01-01
        • 2013-03-08
        • 2021-10-08
        • 2014-07-19
        • 2015-08-09
        • 1970-01-01
        • 2011-04-07
        • 2014-01-25
        相关资源
        最近更新 更多