タイトル
 メニューにないコーナーはTopからいけます
TOPJavaSwingLayoutManager → This Page

絶対位置@Swing LayoutManagerサンプル

概要

Java - Swing - LayoutManager - 絶対位置 のサンプルです。
絶対位置 でコンポーネントをセットする場合に使います。

解説

サンプルを実行すると以下の図のようになります。
サンプル画像

コンテナで setLayout(null); を指定してやると、レイアウトマネージャーが無効になります。
その状態で各コンポーネントで setBounds(X座標, Y座標, 幅, 高さ); を指定すると、
指定した X,Y の座標にコンポーネントが配置されます。

サンプルソース

import java.awt.BorderLayout;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

/**
 * LayoutManager サンプル09
 * ・絶対位置
 * 
 * @author みっちー
 */
public class LayoutManager09 extends JFrame {
	
	/**
	 * 開始メソッド
	 * 
	 * @param args	パラメータ
	 */
	public static void main(String[] args){
		LayoutManager09 frame = new LayoutManager09();
		
		// 閉じるボタンをクリックされた場合の動作を設定
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		// ウインドウのタイトルを設定
		frame.setTitle("LayoutManager サンプル09[絶対位置]");
		
		// フレームの X座標、Y座標、幅、高さを設定
		frame.setBounds(100, 200, 450, 220);
		
		// フレームを表示(これをしないと透明のフレームが立ち上がってしまう)
		frame.setVisible(true);
	}
	
	/**
	 * コンストラクタ
	 */
	public LayoutManager09() {
		// ベースとなるパネルをLayoutManagerを無効にして作成
		JPanel panelBase = new JPanel();
		panelBase.setLayout(null);
		
		// ボタンを作成
		JButton button1 = new JButton("AAAAA");
		JButton button2 = new JButton("BBB");
		JButton button3 = new JButton("CCCCC");
		JButton button4 = new JButton("DDDDDDDD");
		JButton button5 = new JButton("E");
		
		// ボタンの位置を設定
		button1.setBounds(0, 0, 80, 30);
		button2.setBounds(100, 50, 80, 30);
		button3.setBounds(30, 30, 80, 30);
		button4.setBounds(150, 120, 80, 30);
		button5.setBounds(200, 140, 80, 30);
		
		// パネルにボタンを配置
		panelBase.add(button1);
		panelBase.add(button2);
		panelBase.add(button3);
		panelBase.add(button4);
		panelBase.add(button5);
		
		// ベースパネルを追加
		getContentPane().add(panelBase, BorderLayout.CENTER);
	}
}

サンプルソースのダウンロード

ソースのダウンロード(Eclipse用のプロジェクトファイルも同梱)

更新履歴

2016/05/13 Windows 8.1 + Java 7 環境で全体を見直し
2007/12/07 新規作成


TOPJavaSwingLayoutManager → This Page
Valid CSS!