簡體   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