软件编程
位置:首页>> 软件编程>> java编程>> java Swing组件setBounds()简单用法实例分析

java Swing组件setBounds()简单用法实例分析

作者:pzy4447  发布时间:2023-11-23 13:35:54 

标签:java,Swing

本文实例讲述了java Swing组件setBounds()简单用法。分享给大家供大家参考,具体如下:

先看API:

public void setBounds(Rectangle r)

移动组件并调整其大小,使其符合新的有界矩形 r。由 r.x 和 r.y 指定组件的新位置,由 r.width 和 r.height 指定组件的新大小

参数: r - 此组件的新的有界矩形

从API来看,该方法的作用相当于setLocation()setSize()的总和。在实际使用时,需将容器的layout设置为null,因为使用布局管理器时,控件的位置与尺寸是由布局管理器来分配的。需要注意的是,这时必须手动指定容器的尺寸,因为空的布局管理器会将容器自身的PreferredSize清零,导致容器无法在GUI上显示。因此,如果容器在上级容器中使用布局管理器排列,那么需使用setPreferredSize(),如果容器在上级容器中仍然手动排列,那么对容器使用setBounds()即可。

下面是测试demo:


package awtDemo;
import java.awt.Dimension;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class setBoundsDemo {
 public static void main(String[] args) {
   // TODO Auto-generated method stub
   //设置panel的layout以及sieze
   JPanel jpanel = new JPanel();
   System.out.println("default PreferredSize is " + jpanel.getPreferredSize());
   System.out.println("default Size is " + jpanel.getSize());
   jpanel.setLayout(null);
   System.out.println("In null layout, the PreferredSize is " + jpanel.getPreferredSize());
   System.out.println("In null layout, the Size is " + jpanel.getSize());
   jpanel.setPreferredSize(new Dimension(400, 400));
   //添加按钮
   JButton button11 = new JButton("setBounds");
   JButton button12 = new JButton("setLocationAndSetSize");
   button11.setBounds(20, 20, 100, 100);
   button12.setLocation(250, 250);
   button12.setSize(100, 100);
   jpanel.add(button11);
   jpanel.add(button12);
   // 设置窗体属性
   JFrame frame = new JFrame("setBoundsDemo");
   frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   frame.add(jpanel);
   frame.pack();
   frame.setLocationRelativeTo(null);
   frame.setVisible(true);
 }
}

运行效果如下:

java Swing组件setBounds()简单用法实例分析

程序输出如下:


default PreferredSize is java.awt.Dimension[width=10,height=10]
default Size is java.awt.Dimension[width=0,height=0]
In null layout, the PreferredSize is java.awt.Dimension[width=0,height=0]
In null layout, the Size is java.awt.Dimension[width=0,height=0]

希望本文所述对大家java程序设计有所帮助。

来源:https://www.cnblogs.com/pzy4447/p/4574797.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com