如何防止JButton更改大小?

问题描述

我正在玩JFrame窗口(因为我是Java的新手),当我手动最大化JButton时,发现JFrame的大小发生了变化。当我没有最大化屏幕时,它仍然是我设置的大小。

我可以获得任何帮助吗?

这是我的代码:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Frames {
    public static void main(String[] args) {
        Image icon = Toolkit.getDefaultToolkit().getImage("C:\\Users\\admin\\Documents\\Test Stuff\\icon.png");
        JFrame frame = new JFrame("Frame");
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        frame.setLayout(new FlowLayout());
        frame.setSize(856,482);
        frame.setLocation(384,216);
        frame.getContentPane().setBackground( Color.cyan );
        frame.setIconImage(icon);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        JButton buttonClose = new JButton("Close");
        buttonClose.setSize(100,50);
        buttonClose.setLocation(378,10);
        buttonClose.addActionListener(e -> {
            frame.dispose();
        });
        buttonClose.setVisible(true);
        buttonClose.setBackground(Color.green);
        frame.add(buttonClose);
    }
}

解决方法

请勿使用setSize()或setBounds()或setPreferredSize()。

Swing旨在与布局管理器一起使用。

您正在使用FlowLayout。 FlowLayout将遵守按钮的大小。

代码的问题是,在可见该框架之后,将按钮添加到框架,因此最初不调用布局管理器,而是以您为其设置的随机大小显示按钮。当您最大化框架时,将调用布局管理器,以便按钮以其首选大小显示。

在使框架可见之前,应将摆动组件添加到框架中。因此,逻辑的基本顺序应为:

frame.add( button );
frame.setVisible( true );

按钮将以适当的大小显示。

如果您想在按钮的文本周围留有多余的空格,则可以使用按钮的属性来控制它:

JButton button = new JButton(...);
button.setMargin( new Insets(20,20,20) );
,

执行Jarlik所说的话: buttonClose.setPrefferedSize(new Dimension(100,50)); 而不是setSize()。然后将frame.setVisible(true);移到底部。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...