タイトル
TOPJavaSwingJScrollPane → This Page

JScrollPane@Swing サンプル06

概要

Java - Swing - JScrollPane のサンプルです。
・コンポーネントの表示位置を設定

解説

コンポーネントの表示位置を設定します。
ボタンを押すと自動でスクロールし、規定の位置が表示されます。

サンプルイメージ

サンプル画像


サンプルソース

import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JViewport;

/**
 * JScrollPane サンプル06
 * ・コンポーネントの表示位置を設定
 * 
 * @author みっちー
 */
public class JScrollPane06 extends JFrame implements ActionListener {
	
	private static final long serialVersionUID = 1L;
	
	JViewport view;
	
	/**
	 * 開始メソッド
	 * 
	 * @param args	パラメータ
	 */
	public static void main(String[] args) {
		JScrollPane06 frame = new JScrollPane06();
		
		// 閉じるボタンをクリックされた場合の動作を設定
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		// ウインドウのタイトルを設定
		frame.setTitle("JScrollPane サンプル06");
		
		// フレームの X座標、Y座標、幅、高さを設定
		frame.setBounds(100, 200, 380, 250);
		
		// フレームを表示(これをしないと透明のフレームが立ち上がってしまう)
		frame.setVisible(true);
	}
	
	/**
	 * コンストラクタ
	 */
	public JScrollPane06() {
		// パネルを作成
		JPanel panelBase = new JPanel();
		panelBase.setLayout(new BoxLayout(panelBase, BoxLayout.Y_AXIS));
		
		// アイコンを生成
		ImageIcon icon = new ImageIcon("./img/orange.png");
		JLabel label = new JLabel(icon);
		
		// スクロールパネを生成
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setPreferredSize(new Dimension(300, 200));
		
		// Viewportを生成して追加
		view = new JViewport();
		view.setView(label);
		scrollPane.setViewport(view);
		
		// ボタンを生成
		JButton button = new JButton("SET");
		button.addActionListener(this);
		
		// スクロールパネを追加
		panelBase.add(scrollPane);
		panelBase.add(button);
		
		// パネを追加
		getContentPane().add(panelBase);
	}
	
	/**
	 * アクション
	 */
	@Override
	public void actionPerformed(ActionEvent e) {
		view.setViewPosition(new Point(30, 30));
	}
}

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

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

更新履歴

2016/08/25 新規作成


TOPJavaSwingJScrollPane → This Page