JButton在FlowLayout、BorderLayout等一些布局中使用setSize()设置大小无法生效的,可以使用setPreferredSize方法进行设置。 getPreferredSize public Dimension getPreferredSize() 如果preferredSize
已设置为一个非null
值,则返回该值。如果 UI 委托的getPreferredSize
方法返回一个非null
值,则返回该值;否则服从组件的布局管 理器。 setBounds public void setBounds(int x, int y, int width, int height) 移动组件并调整其大小。由x
和y
指定左上角的新位置,由width
和height
指定新的大小。如果width
值或height
值小于之前调用setMinimumSize
指定的最小大小,则它的值将自动增加。
示例: public static void main(String[] args) { JFrame frame = new JFrame(); JButton button = new JButton("按钮"); //设置按钮尺寸 Dimension preferredSize = new Dimension(400,100); button.setPreferredSize(preferredSize ); frame.add(button) frame.setBounds(0,0, 400, 300) frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }