JButton.setBounds(x,y,w,h) 似乎不起作用

Daa*_*ish 3 java swing jbutton layout-manager

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class SimpleExample extends JFrame {

    public SimpleExample() {

        setTitle("Simple example");
        setSize(500, 500);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        JButton jb = new JButton("TEST");
        jb.setBorderPainted(true);
        jb.setBounds(5, 5, 1, 1); ---> This line
        add(jb);

    }

    public static void main(String[] args) {

        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                SimpleExample ex = new SimpleExample();
                ex.setVisible(true);
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

只需创建一个首选大小的简单按钮。该setBounds方法似乎不起作用。我哪里错了?

Mad*_*mer 5

您的框架受布局管理器的控制,它决定如何最好地布局组件并覆盖您使用指定的值 setBounds

现代 GUI 需要在各种不同的图形环境中运行(甚至在同一操作系统上),例如不同的 DPI、屏幕尺寸和字体设置。

布局管理器使您可以(更少)担心这些问题,强烈建议您使用它们

看一眼

更多细节