JButton 不会改变 JPanel 上的大小或位置

问题描述

我在 JPanel 中添加一个按钮并尝试更改按钮的大小和位置。我尝试了不同的代码行,但它们不起作用。同时输入 parent.setLayout(null);panel.setLayout(null); 只会完全删除按钮和背景

代码如下:

import java.awt.BorderLayout;
import java.awt.Color;
import javax.swing.*;

public class app {

    public static void main(final String[] args) {
        final JFrame parent = new JFrame("cps TEST");
        JButton button = new JButton("Button");
        JPanel panel = new JPanel();
        panel.setLayout(null);
        panel.add(button);
        panel.setBackground(Color.DARK_GRAY);
        parent.add(panel,BorderLayout.CENTER);
        parent.setSize(500,300);
        parent.setBackground(Color.CYAN);
        parent.setLocationRelativeto(null);
        parent.setVisible(true);
        parent.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
    }
}

解决方法

以下是增加按钮大小的三种方法:

enter image description here

enter image description here

enter image description here

改变一个组件的位置值得一个单独的问题,但改变一个按钮的大小很容易。