繁体   English   中英

如何在 Java Swing 中设置相同的按钮大小?

[英]How to set size of buttons same in Java Swing?

我是 Swing 新手,并试图为按钮设置相同的大小。 但是,我没有在互联网上找到确切的解决方案。 请注意,我必须使用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();
   }
}

您的问题是 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());
    }
}

代码说明:

千文本字段中列数的常量

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);

注释中有更多解释,尤其是关键方法.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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM