首页 > 解决方案 > 如何使按钮居中并使标题居中?

问题描述

我试图将这两个StartBack按钮居中,但无论何时我尝试任何诸如BoxLayout, .SetLocation, SwingConstant.CENTER,.setVerticalAlignment之类的东西.setHorizonatalAlignment都不起作用。谁能帮我设置中间中间的两个按钮和框架顶部中心的“蛇”标题?谢谢。

package snake;

public class Start {
    public static void main(String[] args) {
        startScreen startFrame = new startScreen();
    }
}

  class startScreen extends JFrame {
      // constructor
      public startScreen() {
          // fonts
          Font snakeTitleFont = new Font("Arial", Font.BOLD, 50);
          Font buttonFont = new Font("Arial", Font.CENTER_BASELINE, 20);

          // text
          JLabel snakeTitle = new JLabel("Snake", SwingConstants.CENTER);
          snakeTitle.setFont(snakeTitleFont);
          add(snakeTitle);

          // start button
          JButton startButton = new JButton("Start");
          startButton.setBackground(Color.MAGENTA);
          startButton.setOpaque(true);
          startButton.setBorderPainted(false);
          startButton.setFont(buttonFont);

          this.setLayout(new BoxLayout(this.getContentPane(), BoxLayout.LINE_AXIS));

          add(startButton);

          // action listener for start btn
          startButton.addActionListener(new ActionListener() {
              // once this is clicked on, it should call the GUI
              @Override
              public void actionPerformed(ActionEvent e) {
                  new Frame();
                  dispose(); // closes the old form after start is clicked
              }
          });

          // back button
          JButton backButton = new JButton("Back");
          backButton.setLayout(null);
          backButton.setBackground(Color.YELLOW);
          backButton.setOpaque(true);
          backButton.setBorderPainted(false);
          backButton.setFont(buttonFont);
          backButton.setBounds(getBounds());
          this.setLayout(new BoxLayout(this.getContentPane(), BoxLayout.LINE_AXIS));

          add(backButton);

          // action listener for start btn
          startButton.addActionListener(new ActionListener() {
              // once this is clicked on, it should call the GUI
              @Override
              public void actionPerformed(ActionEvent e) {
                  new Frame();
                  dispose(); // closes the old form after start is clicked
              }
          });

          this.setVisible(true);
          this.setSize(800, 500);
          this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          this.setResizable(false);
          this.setLocationRelativeTo(null);
      }
  }

标签: javaswinglayout-manager

解决方案


在这里快速浏览一下。最适合您的应用程序的是BoxLayoutFlowLayout

对于各自的使用领域,它们都是非常非常强大的工具。

除此之外,试着看看 Java 的布局教程。您应该始终在 Frames 上使用“ getContentPane() ”方法并应用布局并将组件添加到“ContentPane”!


推荐阅读