setPreferredSize() 在我的 JButton 中不起作用

setPreferredSize() dosent work in my JButton

我正在用 Java 创建一个 Tic Tac Toe 游戏,我似乎在一个我无法解决的问题上陷入困境 :( 。我无法重新调整我的按钮。我尝试了 setSize 和 setPreferredSize但剂量似乎有效:

这里是setPreferedSize图片:

和代码:

import java.awt.Dimension;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import sun.org.mozilla.javascript.internal.xml.XMLLib.Factory;



public class TicTacToe {
    JFrame frame;
    JPanel contentPane;
    JButton row1col1;
    JButton row1col2;
    JButton row1col3;
    JButton row2col1;
    JButton row2col2;
    JButton row2col3;
    JButton row3col1;
    JButton row3col2;
    JButton row3col3;   


    public TicTacToe() {
        // TODO Auto-generated constructor stub

        frame = new JFrame("Fds");
        contentPane = new JPanel();
        contentPane.setLayout(new BoxLayout(contentPane,BoxLayout.Y_AXIS));

        row1col1 = new JButton();
        row1col1.setPreferredSize(new Dimension(600,600));
        contentPane.add(row1col1);

        row1col2 = new JButton();
        row1col2.setPreferredSize(new Dimension(600,600));
        contentPane.add(row1col2);

        frame.setContentPane(contentPane);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);


    }


    private static void runGUI() {
         JFrame.setDefaultLookAndFeelDecorated(true);
         TicTacToe greeting = new TicTacToe();
         }
         public static void main(String[] args) {
         /* Methods that create and show a GUI should be
         run from an event-dispatching thread */
         javax.swing.SwingUtilities.invokeLater(new Runnable() {
         public void run() {
         runGUI();
         }
         });


         }


}

非常感谢您的帮助!

BoxLayout 遵守组件的最大尺寸。

在您的情况下,最大尺寸小于首选尺寸。

但是,解决方案是不要使用 preferred/maximum 尺寸。

您可以使用:

button.setMargin( new Insets(10, 10, 10, 10) );

控制按钮的大小,然后可以进行正常的布局管理,因为首选大小将被正确计算。

正如 Camickr 所说,BoxLayout 尊重最大尺寸,但话说回来,为什么要使用 BoxLayout?相反,我建议:

  • 如果要创建 JButton 网格,请使用 GridLayout,因为它擅长创建网格。
  • 只要您打包 GUI,它就会在某种程度上尊重首选大小,并且所有组件的大小都相同,
  • 不过话虽如此,但不要设置大小。对于井字游戏,将 JLabel 的字体设置为较大的字体,或者将 JLabel 与较大的 ImageIcons 一起使用,以便您的 GUI 正确设置自己的大小。
  • 为了便于编码,您应该使用 JButton 的数组或二维数组。

例如,请在此处查看我的代码:Java: Drawing using Graphics outside the class which draws the main canvas 它使用程序员创建的 ImageIcons 并创建此 GUI:

或者我在这个答案中的代码: 它使用字体大小来创建这个 GUI: