【问题标题】:How to set size of buttons same in Java Swing?如何在 Java Swing 中设置相同的按钮大小?
【发布时间】:2020-04-07 21:39:58
【问题描述】:

我是摇摆新手,我试图为按钮设置相同的大小。但是,我没有在互联网上找到确切的解决方案。 请注意,我必须使用 setPreferredSize()Dimension 目前不是正确的解决方案。我想获取 calcButton 的大小并在 setPreferredSize() 中使用。

图片如下:

和代码:

import javax.swing.*;

/**
   The KiloConverter class displays a JFrame that
   lets the user enter a distance in kilometers. When 
   the Calculate button is clicked, a dialog box is 
   displayed with the distance converted to miles.
*/

public class KiloConverter extends JFrame
{
   private JPanel panel;             // To reference a panel
   private JLabel messageLabel;      // To reference a label
   private JTextField kiloTextField; // To reference a text field
   private JButton calcButton;       // To reference a button
   private JButton alertButton;
   private final int WINDOW_WIDTH = 310;  // Window width
   private final int WINDOW_HEIGHT = 100; // Window height

   /**
      Constructor
   */

   public KiloConverter()
   {
      // Set the window title.
      setTitle("Kilometer Converter");

      // Set the size of the window.
      setSize(WINDOW_WIDTH, WINDOW_HEIGHT);

      // Specify what happens when the close button is clicked.
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      // Build the panel and add it to the frame.
      buildPanel();

      // Add the panel to the frame's content pane.
      add(panel);

      // Display the window.
      setVisible(true);
   }

   /**
      The buildPanel method adds a label, text field, and
      and a button to a panel.
   */

   private void buildPanel()
   {
      // Create a label to display instructions.
      messageLabel = new JLabel("Enter a distance " +
                                "in kilometers");

      // Create a text field 10 characters wide.
      kiloTextField = new JTextField(10);

      // Create a button with the caption "Calculate".
      calcButton = new JButton("Calculate");
      alertButton = new JButton("Alert");
      // --------ERROR HERE----------
      alertButton.setPreferredSize(new getPreferredSize(calcButton));


      // Create a JPanel object and let the panel
      // field reference it.
      panel = new JPanel();

      // Add the label, text field, and button
      // components to the panel.
      panel.add(messageLabel);
      panel.add(kiloTextField);
      panel.add(calcButton);
      panel.add(alertButton);
   }

   /**
      main method
   */

   public static void main(String[] args)
   {
      new KiloConverter();
   }
}

【问题讨论】:

    标签: java swing layout


    【解决方案1】:

    你的问题是一个 XY 问题,你会问“我如何做 'X'?”当更好的解决方案根本不做'X',而是做'Y'时。

    在这里您询问如何设置按钮的首选大小以使按钮大小相等,而更好且实际上规范正确的解决方案不是这样做,而是使用更好的布局管理器,一个为您设置相同大小的按钮 - GridLayout。

    例如,创建一个新的 JPanel 来保存按钮,比如称为 buttonPanel,给它一个 GridLayout,比如 new GridLayout(1, 0, 3, 0),然后将按钮添加到其中,然后将此 JPanel 添加到主 JPanel。

    例如,

    import java.awt.GridLayout;
    import javax.swing.*;
    
    @SuppressWarnings("serial")
    public class LayoutEg extends JPanel {
        private static final int KILO_FIELD_COLS = 15;
        private static final int GAP = 3;
        private JTextField kiloTextField = new JTextField(KILO_FIELD_COLS);
        private JButton calcButton = new JButton("Calculate");
        private JButton alertButton = new JButton("Alert");
    
        public LayoutEg() {
            // add ActionListeners etc.... 
    
            JPanel enterPanel = new JPanel();
            enterPanel.add(new JLabel("Enter a distance in kilometers:"));
            enterPanel.add(kiloTextField);
    
            JPanel buttonPanel = new JPanel(new GridLayout(1, 0, GAP, 0));
            buttonPanel.add(calcButton);
            buttonPanel.add(alertButton);
    
            setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
            setLayout(new GridLayout(0, 1));
            add(enterPanel);
            add(buttonPanel);
        }
    
        private static void createAndShowGui() {
            LayoutEg mainPanel = new LayoutEg();
    
            JFrame frame = new JFrame("Kilometer Converter");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.getContentPane().add(mainPanel);
            frame.pack();
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(() -> createAndShowGui());
        }
    }
    

    代码说明:

    kiloTextField 中的列数常量

    private static final int KILO_FIELD_COLS = 15;
    

    JButton 之间的间隙和主 JPanel 周围的间隙(空边框)的常量

    private static final int GAP = 3;
    

    15 列宽的 JTextField

    private JTextField kiloTextField = new JTextField(KILO_FIELD_COLS);
    

    拥有 JLabel 和 JTextField 的顶级 JPanel。它默认使用 FlowLayout:

    JPanel enterPanel = new JPanel();
    enterPanel.add(new JLabel("Enter a distance in kilometers:"));
    enterPanel.add(kiloTextField);
    

    这是问题的关键,创建一个使用 GridLayout(1, 0, 3, 0) 的 JPanel,这是一个具有 1 行的网格布局,具有 可变 列数(第 0 秒参数)有 3 个水平间隙,没有垂直间隙。然后将我们的按钮添加到其中:

    JPanel buttonPanel = new JPanel(new GridLayout(1, 0, GAP, 0));
    buttonPanel.add(calcButton);
    buttonPanel.add(alertButton);
    

    在这个主 JPanel 周围放置一个 3 像素宽的边框

    setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
    

    给主 JPanel 一个具有可变行数 (0) 和 1 列的 GridLayout,并将 enterPanel 和 buttonPanel 添加到它:

    setLayout(new GridLayout(0, 1));
    add(enterPanel);
    add(buttonPanel);
    

    cmets中的更多解释,尤其是key方法,.pack():

    // create the main JPanel
    LayoutEg mainPanel = new LayoutEg();
    
    // create a JFrame to put it in, although better to put into a JDialog
    JFrame frame = new JFrame("Kilometer Converter");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    // add the LayoutEg JPanel into the JFrame
    frame.getContentPane().add(mainPanel);
    
    // **** key method*** that tells the layout managers to work
    frame.pack();
    
    // center and display
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
    

    【讨论】:

    • 我知道我的解决方案很糟糕 :D 但是我们没用的大学考试会要求在不使用布局的情况下修复它。但是非常感谢您的解释,我也会看看这段代码:)
    • 哦,好吧,实际上它起作用了。我想我可以处理这个解决方案。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-12-06
    • 1970-01-01
    • 2021-02-26
    • 2011-02-01
    • 2014-09-20
    • 1970-01-01
    • 2013-09-21
    • 2012-01-01
    相关资源
    最近更新 更多