如何解决第二个按钮尺寸设置失败?

运行结果

img


package com.test;

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

public class MyJFrame extends JFrame implements ActionListener {
    JButton jbt1=new JButton("点我");
    JButton jbt2=new JButton("点不到我");
    public MyJFrame(){
        initJframe();

        jbt1.setBounds(0,0,100,50);
        jbt1.addActionListener(this);
        jbt2.setBounds(100,0,10,5);
        jbt2.addActionListener(this);
        this.getContentPane().add(jbt1);
        this.getContentPane().add(jbt2);

    }

    private void initJframe() {
        this.setSize(500,500);
        this.setAlwaysOnTop(true);
        this.setTitle("MyJFrame");
        this.setLocationRelativeTo(null);
        this.setDefaultCloseOperation(3);this.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Object sourse=e.getSource();
        if(sourse==jbt1){
            jbt1.setSize(200,100);
        }
        else if(sourse==jbt2){
            jbt2.setLocation(new Random().nextInt(500),new Random().nextInt(500));
        }
    }
}

需要指定 自定义JFrame的布局管理器为空

this.setLayout(null);

img

img


如有帮助,欢迎采纳哈!

在这里插入图片描述

本人的开源项目,欢迎star支持下!!!