JButton.setBounds(x,y,w,h)似乎不起作用
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); } }); } }
只需创建一个首选大小的简单按钮。 setBounds
方法似乎不起作用。 我哪里错了?
您的框架受布局管理器的控制,它正在决定如何最好地布局组件,并使用setBounds
覆盖您指定的值
现代GUI需要在各种不同的图形环境中运行(甚至在相同的OS上),例如包括不同的DPI,屏幕尺寸和字体设置。
布局管理器使您可以(较少)担心这些问题,强烈建议您使用它们
看一眼
- 使用布局管理器
- 布局管理器的可视指南
更多细节
作为一种好的做法,您不应该将按钮直接添加到JFrame
。 而是将JPanel
添加到框架,将面板的布局设置为null
,并将JButton
添加到JPanel
。