package swing.chapter02; import swing.util.SwingConsle; import javax.swing.*; import java.awt.*; /** * 绝对定位 */ public class NullLayout extends JFrame { private JButton b1 = new JButton("Button 1"), b2 = new JButton("Button 2"); public NullLayout(){ // 把布局管理器设置为空 setLayout(null); // 为 JButton 设置边界矩形参数,达到绝对定位 b1.setBounds(new Rectangle(30,30, 100, 100)); add(b1); b2.setBounds(new Rectangle(130,80, 100, 50)); add(b2); } public static void main(String[] args) { SwingConsle.run(new NullLayout(), 500, 500); } }
package swing.util; import javax.swing.*; /** * 显示框架工具类 */ public class SwingConsle { public static void run(JFrame f, final int width, final int height){ SwingUtilities.invokeLater(new Runnable() { @Override public void run() { f.setTitle(f.getClass().getSimpleName()); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(width, height); f.setVisible(true); } }); } }
运行效果: