SQLの窓

2018年07月06日


WindowBuilder JFace : WEB より JSON を取得して Table に表示する

Okhttp(ダウンロード) を使用した HttpAccess クラス を使用して、WEB 上から JSON 文字列を取得して Table コントロールにデータの一覧を表示します。
(重要) Okio(ダウンロード) も必要です

JSON 文字列を オブジェクトに変換する為に、Google Gson(各バージョンダウンロードページ) を使用します

使用するのは fromJson メソッドのみです。
// ▼ オブジェクト化用クラス定義
// JSON のプロパティ名と 以下のフィールド名が一致します
private class MyData {
	String 社員コード;
	String 氏名;
	String フリガナ;
	String 所属;
	String 性別;
	String 作成日;
	String 更新日;
	String 給与;
	String 手当;
	String 管理者;
	String 生年月日;
}
--------------------------------------------------------
// ▼ 使用方法
// JSON 文字列 => オブジェクト用
Gson gson = new Gson();
 
// JSON では、{} が配列となっています
MyData[] array = gson.fromJson(s, MyData[].class);
--------------------------------------------------------
// ▼ データ( 一件分 )
[
    {
        "社員コード": "0001",
        "氏名": "山田 太郎",
        "フリガナ": "ウラオカ トモヤ",
        "所属": "0003",
        "性別": "0",
        "作成日": "2005-09-12 00:00:00",
        "更新日": "2005-11-28 00:00:00",
        "給与": "1002",
        "手当": "9000",
        "管理者": "0001",
        "生年月日": "2012\/03\/21"
    }
]
データを MyData のインスタンスとして取得した後、MyData のクラス定義より、java.lang.reflect.Field (getName メソッド) を使用してデータのタイトル用に MyData のフィールド名を取得します。さらに、get メソッドを使用してデータを取得して Table コントロールに反映させます。
// MyData のフィールドよりタイトルを作成
Field[] flds = MyData.class.getDeclaredFields();
int fldCount = 0;
for( Field fld : flds ) {
	// このクラス名 "Main" を排除
	if ( !fld.getType().getName().equals("Main") ) {
		// 列
		tableColumn = new TableColumn(table, SWT.NONE);
		// 表示幅
		tableColumn.setWidth(100);
		// タイトルとして、フィールド名
		tableColumn.setText(fld.getName());

		// 列数
		fldCount++;
	}
}
※ 1行目の getDeclaredFields メソッドは、java.lang.Class.getDeclaredFields

Table コントロールは、org.eclipse.swt.widgets.Table です。

▼ 列定義用
TableColumn
▼ 行データ用
TableItem
// 列数ぶん配列を作成
String[] columnData = new String[fldCount];
 
// データを一行ぶん作ったら...

// 行作成( Table と関係づけ )
tableItem = new TableItem(table, SWT.NONE);
// 列データを配列で一括設定( 配列で一括設定 )
tableItem.setText(columnData);

// public void setText(String[] strings)
// Sets the text for multiple columns in the table.
// Note: If control characters like '\n', '\t' etc. are used in the string, 
// then the behavior is platform dependent.
// 
// Parameters:
// strings - the array of new strings
※ メニューの作成は、『Pleiades Oxygen + WindowsBuilder で MySQL を使用して SQL(select) からデータの一覧を表示する』を参照して下さい。
import java.lang.reflect.Field;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;

import com.google.gson.Gson;

public class Main extends ApplicationWindow {

	private Table table;
	private String url = "http://localhost/web/form/basic-php-0628-iframe-client/data.php";
	private HttpAccess httpAccess;

	// メニユーアイテム
	private Action action;

	private class MyData {
		String 社員コード;
		String 氏名;
		String フリガナ;
		String 所属;
		String 性別;
		String 作成日;
		String 更新日;
		String 給与;
		String 手当;
		String 管理者;
		String 生年月日;
	}

	// *******************************
	// コンストラクタ
	// *******************************
	public Main() {
		super(null);
		createActions();
		addMenuBar();
		httpAccess = new HttpAccess(url);
	}

	// *******************************
	// コントロール追加
	// *******************************
	@Override
	protected Control createContents(Composite parent) {
		Composite container = new Composite(parent, SWT.NONE);
		container.addControlListener(new ControlAdapter() {
			@Override
			public void controlResized(ControlEvent e) {

				Rectangle size = container.getClientArea();
				table.setSize(size.width-21, size.height-84);

			}
		});

		// *******************************
		// ボタン
		// *******************************
		Button btnNewButton = new Button(container, SWT.NONE);
		btnNewButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				table.removeAll();
				loadMySQL();
			}
		});
		btnNewButton.setBounds(10, 10, 75, 25);
		btnNewButton.setText("実行");

		// *******************************
		// テーブル
		// *******************************
		table = new Table(container, SWT.BORDER | SWT.FULL_SELECTION);
		table.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseDoubleClick(MouseEvent e) {

				int row_no = table.getSelectionIndex();
				// 行 は 0 以上
				if ( row_no >= 0 ) {

					// タイトル部分の表示
					TableColumn[] tableColumns = table.getColumns();
					for( TableColumn column: tableColumns ) {
						System.out.println( column.getText() );
					}

					// 行部分の表示
					TableItem tableItem = table.getItem(row_no);
					int columnCount = tableColumns.length;
					for( int i = 0; i < columnCount; i++ ) {
						System.out.println( tableItem.getText(i));
					}

				}
			}
		});
		table.setBounds(10, 41, 591, 333);
		table.setHeaderVisible(true);
		table.setLinesVisible(true);

		return container;
	}

	// *******************************
	// データ表示
	// *******************************
	protected void loadMySQL() {

		// 引数のインターフェイスが内部より呼ばれる
		httpAccess.sendGet(new HttpAccess.SendGetListener() {

			// インターフェイス内で定義したメソッド
			public void sendGetListener(String s) {
				
				if ( s.equals("{}")) { 
					MessageBox message = new MessageBox(Main.this.getShell(),SWT.OK);
					message.setMessage("データを取得できませんでした");
					message.open();
					return;
				}

				// JSON 文字列 => オブジェクト用
				Gson gson = new Gson();

				// JSON では、{} が配列となっています
				MyData[] array = gson.fromJson(s, MyData[].class);

				// 列定義用
				TableColumn tableColumn = null;

				// MyData のフィールドよりタイトルを作成
				Field[] flds = MyData.class.getDeclaredFields();
				int fldCount = 0;
				for( Field fld : flds ) {
					// このクラス名 "Main" を排除
					if ( !fld.getType().getName().equals("Main") ) {
						// 列
						tableColumn = new TableColumn(table, SWT.NONE);
						// 表示幅
						tableColumn.setWidth(100);
						// タイトルとして、フィールド名
						tableColumn.setText(fld.getName());

						// 列数
						fldCount++;
					}
				}

				// 行
				TableItem tableItem = null;

				// array に MyData の配列が格納されています
				for (MyData data: array) {

					// 列数ぶん配列を作成
					String[] columnData = new String[fldCount];

					// 配列参照用
					int idx = 0;
					// フィールド単位でデータを取得する
					for( Field fld : flds ) {
						// このクラス名 "Main" を排除
						if ( !fld.getType().getName().equals("Main") ) {
							try {
								if ( fld.get( data ) == null ) {
									// データが NULL の場合は空白
									columnData[idx] = "";
								}
								else {
									columnData[idx] = fld.get( data ).toString();
								}
							} catch (Exception e) {
								// エラーの場合は空白
								columnData[idx] = "";
							}
							idx++;

						}
					}

					// 行作成
					tableItem = new TableItem(table, SWT.NONE);
					// 列データを配列で一括設定
					tableItem.setText(columnData);

				}

			}

		});


	}

	// *******************************
	// メニューのアイテム
	// *******************************
	private void createActions() {
		// Create the actions
		{
			action = new Action("実行") {

				@Override
				public void run() {
					table.removeAll();
					loadMySQL();
				}

			};
		}
	}

	// *******************************
	// メニュー
	// *******************************
	@Override
	protected MenuManager createMenuManager() {
		MenuManager menuManager = new MenuManager("menu");

		MenuManager menuManager_item = new MenuManager("メニュー");
		menuManager.add(menuManager_item);
		menuManager_item.add(action);
		return menuManager;
	}

	// *******************************
	// エントリポイント
	// *******************************
	public static void main(String args[]) {
		try {
			Main window = new Main();
			window.setBlockOnOpen(true);
			window.open();
			Display.getCurrent().dispose();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// *******************************
	// Shell の初期処理
	// *******************************
	@Override
	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setText("タイトル");
	}

	// *******************************
	// 画面の初期処理
	// *******************************
	@Override
	protected Point getInitialSize() {
		return new Point(800, 600);
	}
}



HttpAccess クラス

SendGetListener インターフェイスを定義して、JSON 文字列を受信した後の処理を、呼び出し元で処理させるようにしています。=> ※ listner.sendGetListener(data); の部分
import java.io.IOException;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HttpAccess {

	private OkHttpClient okHttpClient;
	private String url;

	// 受信イベント
	public interface SendGetListener {
		abstract public void sendGetListener(String s);
	}

	// コンストラクタ
	public HttpAccess(String url) {

		this.okHttpClient = new OkHttpClient();
		this.url = url;

	}

	public HttpAccess() {
		this.okHttpClient = new OkHttpClient();
	}

	public void setUrl(String url) {
		this.url = url;
	}


	public void sendGet(SendGetListener listner) {

		// 汎用的に 初期値は {} としています
		String data = "{}";

		Request.Builder builder = new Request.Builder();
		builder.url(url);
		Request request = builder.build();

		Response response = null;
		try {
			response = HttpAccess.this.okHttpClient.newCall(request).execute();
			data = response.body().string();
		}
		catch (IOException e) {
			e.printStackTrace();
		}

		listner.sendGetListener(data);

	}

}


関連する記事

Pleiades Oxygen + WindowsBuilder で MySQL を使用して SQL(select) からデータの一覧を表示する






posted by lightbox at 2018-07-06 13:55 | java : WindowBuilder | このブログの読者になる | 更新情報をチェックする

2018年06月19日


Pleiades All in One で、Windows アプリを作成する手順( WindowBuilder + Swing デザイナー or SWT デザイナー[JFace] )

関連する記事

Pleiades Eclipse 4.7 Oxygen 2 Windows 64bit Ultimate Full Edition のインストールといろいろな準備
Pythonの開発環境、Ruby( 本体は別インストール ) の開発環境、XAMPP が同梱されます
2018年05月15日 時点 Eclipse 4.7 Oxygen3 が最新バージョンなので、64bit版の Java Full Edition をダウンロードします。 ※ jface のプラグインの修正が必要ありません 2017年04月15日 時点 Eclipse 4.6 Neon 3 が最新バージョンなので、64bit版の Java Full Edition をダウンロードします。 Java だけではなく、Tomcat(6,7,8)JDK(6u48,7u80,8u121) も同梱されており、いろいろ便利に使えます。 解凍 Pleiades のダウンロードファイル(1.01G)はとても名前が長いので、Pleiades.zip に変更し、c:\ に移動してから 7-zip で解凍します。(昔から Pleiades で注意がうながされている、パスの長さの制限に対するものです) jface プラグインの手動整備 Oxygen : 必要ありません Neon : 必要です Mars : ? Luna : 必要ありません ファイルをリネームするだけです。理由は解りませんが、本来の正しいファイルが .backup となっているので、.backup の無いファイルは適当なファイル名にして、.backup の付いたファイルを正式なファイルにします。 ▼ リネーム前 ▼ リネーム後 これは、Eclipse 4.4 Luna では必要無いのですが、たしか、Eclipse 4.5 Mars でも必要があると思います。これをしないと、実行時にエラーが発生します。(フォント用のプロパティファイルが、存在しないため) 最初の実行 Pleiades は、最初と、環境が変わった際に、以下を実行するように強く推奨されています。 eclipse.exe -clean.cmd WindowBuilder のインストール WindowBuilder のサイトよりインストール用の URL を取得します。 ▼ Oxygen ▼ Neon リンク先の URL をクリップボードにコピーします。そして、HELP => 新規ソフトウェアのインストール で、『作業対象』に URL を貼り付けて Enter キーを押して下さい。 WindowBuilder が表示されたら、チェックしてインストールを進めます。 SWT デザイナー[JFace] を使う場合 プロジェクトは専用のものを使いますので、『その他』から以下を選択して下さい。 プロジェクトを作成したら、CTRL+N でその他より、以下を選択して下さい。 実行してウインドウが表示されたら準備完了です。 Swing デザイナー を使う場合 この場合は、プラグインのリネームは必要ありません。プロジェクトも通常の Java プロジェクトで以下を選択します。 これも、実行してウインドウが表示されたら準備完了です。
posted by lightbox at 2018-06-19 11:02 | java : WindowBuilder | このブログの読者になる | 更新情報をチェックする

2017年06月10日


WindowBuilder(Swing) で、WEBカメラを使用して画像を保存して okhttp で WEBサーバへアップロードする



必要なライブラリ

アップロードには okhttp を使用します
( ライブラリとしては okio も必要です )

JFrame を新しく作成して WEBカメラの映像をリアルタイムに表示しています。ライブラリは、webcam-capture を使用していますが、他のライブラリとして bridj-0.6.2.jar と slf4j-api-1.7.2.jar が同梱されていましたが、slf4j はもっと新しいバージョンがあり、いずれにしても slf4j-nop-1.7.25.jar が必要だったので、現時点で最新版の slf4j-api-1.7.25.jar をダウンロードして使用しました。


( Failed to load class org.slf4j.impl.StaticLoggerBinder が出る場合 )

単純な環境ならば、Maven が簡単です。(一つの IP で多くのアクセスがある場合は問題が出ます)

配布元のサンプルコード

How to display image from webcam in Swing panel (basic)

JFrame にロードする場合は、自動的に open されるようです。

WindowBuildewr のソースコード

プロジェクトの作成は、通常プロジェクトに WindowBuilder の JFrame を作成したものです。WindowBuilder の導入は『Pleiades All in One(NEON) で、Windows アプリを作成する手順( WindowBuilder + Swing デザイナー or SWT デザイナー[JFace] )』を参照して下さい
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamPanel;
import com.github.sarxos.webcam.WebcamResolution;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Main extends JFrame {

	private JPanel contentPane;
	private Webcam webcam;

	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Main frame = new Main();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	public Main() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 559, 444);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);

		JButton btnNewButton = new JButton("New button");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {

				File targetFile;

				// get image
				BufferedImage image = webcam.getImage();
				// save image to PNG file
				targetFile = new File("c:\\temp\\test.png");
				try {
					ImageIO.write(image, "PNG", targetFile);
				} catch (IOException e1) {
					// TODO 自動生成された catch ブロック
					e1.printStackTrace();
				}


				OkHttpClient client = new OkHttpClient();

				MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder();
				multipartBodyBuilder.setType(MultipartBody.FORM);
				multipartBodyBuilder.addFormDataPart(
					"target",
					targetFile.getName(),
					RequestBody.create(MediaType.parse("image/png"),targetFile)
				);
				RequestBody requestBody = multipartBodyBuilder.build();

				// 送信用のデータを作成
				Request.Builder requestBuilder = new Request.Builder();
				String url = "https://ドメイン/パス/file_upload.php";
				requestBuilder.url(url);
				requestBuilder.post(requestBody);
				Request request = requestBuilder.build();

				// 受信用のオブジェクトの準備
				Call call = client.newCall(request);
				String result = "";

				// 送信と受信
				try {

					Response response = call.execute();
					result = response.body().string();

				} catch (Exception ex) {
					ex.printStackTrace();
				}

				System.out.println(result);

			}
		});
		btnNewButton.setBounds(12, 10, 135, 21);
		contentPane.add(btnNewButton);

		loadWebCam();
	}

	private void loadWebCam(){

		webcam = Webcam.getDefault();
		webcam.setViewSize(WebcamResolution.VGA.getSize());

		WebcamPanel panel = new WebcamPanel(webcam);
		panel.setFPSDisplayed(true);
		panel.setDisplayDebugInfo(true);
		panel.setImageSizeDisplayed(true);
		panel.setMirrored(true);

		JFrame window = new JFrame("Webcam Panel");
		window.getContentPane().add(panel);
		window.setResizable(true);
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.pack();
		window.setVisible(true);


	}
}


WEBサーバの PHP

アップロードの name は target で固定です。
<?php
session_cache_limiter('nocache');
session_start();

header( "Content-Type: application/json; charset=utf-8" );


if ( $_SERVER['REQUEST_METHOD'] == "POST" ) {
 
	$upload = realpath ( '.' );
	$upload .= ( DIRECTORY_SEPARATOR . $_FILES['target']['name'] );
	if ( move_uploaded_file(
		$_FILES['target']['tmp_name'], $upload ) ) {
		$_POST['result']  = "アップロードに成功しました";
	}
	else {
		$_POST['result']  = "アップロードに失敗しました";
	}

}
else {
	$_POST['result']  = "POST メソッドを使用して下さい";
}

$_POST['files'] = $_FILES;

print json_encode($_POST, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE );
?>


関連する記事

PHP : MastodonOAuthPHP の HttpRequest.php の http_request を public に書き換えて、ファイルアップロード


メインの JFrame 内の JPanel に表示する



	private void loadWebCam(){

		webcam = Webcam.getDefault();
		webcam.setViewSize(WebcamResolution.VGA.getSize());

		WebcamPanel panel = new WebcamPanel(webcam);
		panel.setFPSDisplayed(true);
		panel.setDisplayDebugInfo(true);
		panel.setImageSizeDisplayed(true);
		panel.setMirrored(true);

		panelInFrame.add(panel);

	}

IP カメラを使用する場合

ライブラリのダウンロード(webcam-capture-driver-ipcam)

IP カメラは、WEBカメラを Gmax M-JPEG version を使用しています( exe ファイルを VirusTotal でチェックししています )
	// ***************************
	// JFrame に IP Cam
	// ***************************
	private void loadIpWebCam(){

		Webcam.setDriver(new IpCamDriver());

		try {
			IpCamDeviceRegistry.register(new IpCamDevice("lightbox", "http://192.168.1.4:8088/", IpCamMode.PUSH));
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}

		JFrame window = new JFrame("Webcam Panel");
		window.getContentPane().add(new WebcamPanel(Webcam.getDefault()));
		window.setResizable(true);
		window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		window.pack();
		window.setVisible(true);
		
		webcam = Webcam.getDefault();

	}

	// ***************************
	// JFrame 内の JPanel に IP Cam
	// ***************************
	private void loadIpWebCam2(){

		Webcam.setDriver(new IpCamDriver());

		try {
			IpCamDeviceRegistry.register(new IpCamDevice("lightbox", "http://192.168.1.4:8088/", IpCamMode.PUSH));
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}

		panelInFrame.add(new WebcamPanel(Webcam.getDefault()));

		webcam = Webcam.getDefault();
	}



posted by lightbox at 2017-06-10 23:40 | java : WindowBuilder | このブログの読者になる | 更新情報をチェックする

2016年05月29日


Java WindowBuilder から超簡易掲示板(CSVタイプ)投稿

HttpPost クラスのテストです。



超簡易掲示板(CSV)は以下からダウンロードできます。

超簡易掲示板 : 保存タイプは CSV

WindowBuilder 側では、複数行のテキストフィールドを使って単純投稿です。
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import com.google.gson.Gson;


public class TopWindow extends ApplicationWindow {

	private int width = 600;
	private int height = 440;
	private Gson gson;
	private Text text;

	// *********************************
	// コンストラクタ
	// *********************************
	public TopWindow() {
		super(null);
	}

	// *********************************
	// コントロールの追加
	// ※ Design での変更が反映されます
	// *********************************
	@Override
	protected Control createContents(Composite parent) {
		Composite container = new Composite(parent, SWT.NONE);

		// ボタンの定義
		Button button = new Button(container, SWT.NONE);
		// ボタンのイベント
		button.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {

				// プログラム開始時に実行すると、固まるので直前に
				try {
					UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
				} catch (ClassNotFoundException | InstantiationException
						| IllegalAccessException
						| UnsupportedLookAndFeelException e1) {
					e1.printStackTrace();
				}

				// 確認ダイアログ( OK_CANCEL )の表示
				int result = JOptionPane.showConfirmDialog(
						null,
						"データを POST しますか",
						"確認",
						JOptionPane.OK_CANCEL_OPTION,
						JOptionPane.QUESTION_MESSAGE);
				// OK を選択
				if ( result == JOptionPane.OK_OPTION ) {

					// POST データ
					Map<String,String> param = new HashMap<String,String>();
					param.put("send", "send");
					param.put("subject", "テスト投稿");
					param.put("name", "ウインドウビルダー");
					param.put("text", text.getText());
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
					param.put("datetime", sdf.format(new Date()));

					// インターネットアクセス
					String data = HttpPost.execute("http://localhost/log/easy_board/csvtype/board.php", param, "utf-8");
					// データを取得できた
					if ( !data.equals("") ) {
						// コンソールで確認
						System.out.println(data);
					}
				}
			}
		});
		button.setBounds(10, 10, 81, 28);
		button.setText("実行");
		
		text = new Text(container, SWT.BORDER | SWT.MULTI);
		text.setBounds(10, 44, 483, 341);


		return container;
	}

	// *********************************
	// アプリケーションの開始
	// *********************************
	public static void main(String args[]) {
		try {
			// 自分自身(TopWindow) の作成
			TopWindow window = new TopWindow();
			// open を実行したら、Window を閉じるまで次の行を実行しない
			window.setBlockOnOpen(true);
			window.open();
			// Window を閉じたら以下を実行してアプリケーションを終了する
			Display.getCurrent().dispose();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// *********************************
	// Window の初期設定
	// *********************************
	@Override
	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);

		// タイトルの設定
		newShell.setText("タイトル文字列");

	}

	// *********************************
	// Window サイズの初期設定
	// *********************************
	@Override
	protected Point getInitialSize() {
		// プライベート変数を使用してウインドウサイズを決定しています
		return new Point(width, height);
	}

}


プロジェクトを一から作る方法


posted by lightbox at 2016-05-29 22:48 | java : WindowBuilder | このブログの読者になる | 更新情報をチェックする

2016年05月22日


WindowBuilder のテーブルコントロールにインターネットから JSON データを読み込んで処理するテンプレート





インターネットからデータを読み込むのに、HttpGet というクラスをソースで同梱しています。プロジェクトのインポート方法は、『Eclipse 4.4 Pleiades + WindowBuilder テンプレート / アプリケーションウインドウとダイアログ』を参照して下さい。

JSON データを扱う Google Gson は、ライブラリとしては同梱しています。ダウンロードはこちら(GitHub のページ)です。※ ページ内の Gson Download のリンクからダウンロードページへ移動します

処理概要

1) ボタンをクリックすると、お天気Webサービス仕様 - Weather Hacks - livedoor 天気情報 の 『大阪の』JSON データを取得します。

2) 場所の名前と、地域コードを二つの列に表示し、行の内部コードとして URL を格納します

3) 行をダブルクリックすると、URL を使用してブラウザで開きます

ソースコード
import java.awt.Desktop;
import java.net.URI;

import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

import org.eclipse.jface.window.ApplicationWindow;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;

import com.google.gson.Gson;


public class TopWindow extends ApplicationWindow {

	private int width = 800;
	private int height = 600;
	private Table table;
	private Gson gson;

	// *********************************
	// コンストラクタ
	// *********************************
	public TopWindow() {
		super(null);
	}

	// *********************************
	// コントロールの追加
	// ※ Design での変更が反映されます
	// *********************************
	@Override
	protected Control createContents(Composite parent) {
		Composite container = new Composite(parent, SWT.NONE);

		// ボタンの定義
		Button button = new Button(container, SWT.NONE);
		// ボタンのイベント
		button.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				
				// プログラム開始時に実行すると、固まるので直前に
				try {
					UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
				} catch (ClassNotFoundException | InstantiationException
						| IllegalAccessException
						| UnsupportedLookAndFeelException e1) {
					e1.printStackTrace();
				}
				
				// 確認ダイアログ( OK_CANCEL )の表示
				int result = JOptionPane.showConfirmDialog(
						null,
						"データを取得しますか",
						"確認",
						JOptionPane.OK_CANCEL_OPTION,
						JOptionPane.QUESTION_MESSAGE);
				// OK を選択
				if ( result == JOptionPane.OK_OPTION ) {
					// インターネットアクセス
					String data = HttpGet.execute("http://weather.livedoor.com/forecast/webservice/json/v1?city=270000", "utf-8");
					// データを取得できた
					if ( !data.equals("") ) {
						// コンソールで確認
						System.out.println(data);
						// JSON をオブジェクト化する為の GSON を作成
						gson = new Gson();
						// データに適合するプライベートクラスで変換
						Weather weatherData = gson.fromJson(data, Weather.class);
						// データ行数
						int length = weatherData.pinpointLocations.length;

						// 行データ格納用
						TableItem tableItem;
						// 列データ格納用
						String[] columnData = new String[2];
						for( int i = 0; i < length; i++) {
							// 確認用の表示
							System.out.println(String.format("name:%s, link:%s",
									weatherData.pinpointLocations[i].name,
									weatherData.pinpointLocations[i].link
								)
							);
							// 場所名
							columnData[0] = weatherData.pinpointLocations[i].name;
							// livedoor の個別コード
							columnData[1] = weatherData.pinpointLocations[i].link.replace("http://weather.livedoor.com/area/forecast/", "");
							// 行を Table から新しく取得
							tableItem = new TableItem(table, SWT.NONE);
							// 行に表示用の配列データをセット
							tableItem.setText(columnData);
							// livedoor の個別天気表示 URL を内部データとしてセット
							tableItem.setData(weatherData.pinpointLocations[i].link);
							
						}
					}
				}
			}
		});
		button.setBounds(10, 10, 81, 28);
		button.setText("実行");

		// Table の定義
		table = new Table(container, SWT.BORDER | SWT.FULL_SELECTION);
		table.addMouseListener(new MouseAdapter() {
			
			// テーブルをダブルクリック
			@Override
			public void mouseDoubleClick(MouseEvent e) {
				int row_no = table.getSelectionIndex();
				// 行が内ばあいは row_no は -1
				System.out.println( String.format("row_no : %d",row_no) );
				// 行データがあり、任意の行の上でダブルクリックした場合
				if ( row_no >= 0 ) {
					// タイトル部分の表示
					TableColumn tableColumn;
					tableColumn = table.getColumn(0);
					System.out.println( tableColumn.getText() );
					tableColumn = table.getColumn(1);
					System.out.println( tableColumn.getText() );

					// 行部分の表示
					TableItem tableItem = table.getItem(row_no);
					// 名前の表示
					System.out.println( tableItem.getText(0) );
					// コードの表示
					System.out.println( tableItem.getText(1) );
					// URL の表示
					System.out.println( tableItem.getData() );
					
					// プログラム開始時に取得すると、固まるので直前に
					// ブラウザを開く
					Desktop desktop = Desktop.getDesktop();
					try {
						URI uri = new URI((String) tableItem.getData());
						desktop.browse(uri);
					} catch (Exception ex) {
						ex.printStackTrace();
					}				
					
				}
			}
		});
		table.setBounds(10, 50, 764, 498);
		table.setHeaderVisible(true);
		table.setLinesVisible(true);
		
		// 列の作成
		TableColumn tableColumn = new TableColumn(table, SWT.NONE);
		tableColumn.setWidth(100);
		tableColumn.setText("名前");

		TableColumn tableColumn_1 = new TableColumn(table, SWT.NONE);
		tableColumn_1.setWidth(131);
		tableColumn_1.setText("コード");


		return container;
	}

	// *********************************
	// アプリケーションの開始
	// *********************************
	public static void main(String args[]) {
		try {
			// 自分自身(TopWindow) の作成
			TopWindow window = new TopWindow();
			// open を実行したら、Window を閉じるまで次の行を実行しない
			window.setBlockOnOpen(true);
			window.open();
			// Window を閉じたら以下を実行してアプリケーションを終了する
			Display.getCurrent().dispose();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// *********************************
	// Window の初期設定
	// *********************************
	@Override
	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);

		// タイトルの設定
		newShell.setText("タイトル文字列");

		// アイコンの設定
		ImageData id = new ImageData("image/lightbox.png");
		Image img = new Image(newShell.getDisplay(), id);
		newShell.setImage(img);

	}

	// *********************************
	// Window サイズの初期設定
	// *********************************
	@Override
	protected Point getInitialSize() {
		// プライベート変数を使用してウインドウサイズを決定しています
		return new Point(width, height);
	}
	
	// Livedoor の お天気Webサービス用 (配列データ用)
	private class PinpointLocation {
		String link;
		String name;
		public PinpointLocation(String myLink, String myName) {
			name = myName;
			link = myLink;
		}

		@Override
		public String toString() {
			return name;
		}
	}
	// Livedoor の お天気Webサービス用 (JSON用)
	private class Weather {
		PinpointLocation[] pinpointLocations;
	}	
}

どのような環境でも発生するのかどうかわかりませんが、UIManager.setLookAndFeel の実行場所によって、JOptionPane のメッセージボックスで固まったり、Desktop.getDesktop() の実行場所によっても固まったりしたので、変数の置き場所を実行ブロック内にしています。



posted by lightbox at 2016-05-22 19:10 | java : WindowBuilder | このブログの読者になる | 更新情報をチェックする

2016年05月07日


WindowBuilder テンプレートのテーブルコントロールに MySQL のデータを表示する

▼ テンプレートはこちらから
Eclipse 4.4 Pleiades + WindowBuilder テンプレート / アプリケーションウインドウとダイアログ



テンプレートにはあらかじめ Table コントロールを配置しています。元々のコードは上のリンク先を参照して下さい。こちらでは、追加として MySQL の mysql-connector-java-5.1.30-bin.jar をプロジェクト内に lib フォルダを作成してコピーしています。
※ ファイルシステムからコピーして、プロジェクトツリーからリフレッシュすると表示されます

その後、mysql-connector-java-5.1.30-bin.jar を右クリックして『ビルド・パス』を開くと追加のメニューが現れるので実行すると使えるようになります。

SQL をテキストファイルから読み込む static メソッド

TopWindow の中に追加して使います
	static String loadText(String name) throws Exception {

		FileInputStream fis = new FileInputStream(name);
		int size = fis.available();
		InputStreamReader isr = new InputStreamReader(fis);
		BufferedReader br = new BufferedReader(isr);
		StringBuffer all_string = new StringBuffer(size);
		String str = null;
		while ((str = br.readLine()) != null) {
			// 初回以外は前に改行を挿入する
			if (!all_string.toString().equals("")) {
				all_string.append("\n");
			}
			all_string.append(str);
		}
		br.close();

		return all_string.toString();

	}	
後は、Dialog1 の初期表示で MySQL からデータを読み込みます

Dialog1.java
import java.awt.GraphicsEnvironment;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;


public class Dialog1 extends Dialog {

	private int width = 800;
	private int height = 600;
	private Table table;
	private Connection con;
	private Statement stmt;
	private ResultSet rset;
	// *********************************
	// コンストラクタ
	// *********************************
	public Dialog1(Shell parentShell) {
		super(parentShell);
	}

	// *********************************
	// コントロールの追加
	// ※ Design での変更が反映されます
	// *********************************
	@Override
	protected Control createDialogArea(Composite parent) {
		Composite container = (Composite) super.createDialogArea(parent);

		// テーブルの作成
		table = new Table(container, SWT.BORDER | SWT.FULL_SELECTION);
		table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
		table.setHeaderVisible(true);
		table.setLinesVisible(true);

		// 列の作成
		TableColumn tableColumn = new TableColumn(table, SWT.NONE);
		tableColumn.setWidth(100);
		tableColumn.setText("名前");

		TableColumn tableColumn_1 = new TableColumn(table, SWT.NONE);
		tableColumn_1.setWidth(131);
		tableColumn_1.setText("詳細");
		String connectionString = "jdbc:mysql://localhost/lightbox?" +
				"user=root&password=パスワード";

		TableItem tableItem;
		String[] columnData = new String[2];
		try {
			con = DriverManager.getConnection(connectionString);
			stmt = con.createStatement();

			rset = stmt.executeQuery ( TopWindow.loadText("data/sql1.txt") );

			ResultSetMetaData rm = rset.getMetaData();
			int nCols = rm.getColumnCount();
			String[] data = new String[nCols];
			int i;

			while( rset.next() ) {
				for( i = 0; i < nCols; i++ ) {
					data[i] = rset.getString( i+1 );

					if ( i != 0 ) {
						System.out.print( "," );
					}
					System.out.print( data[i] );
				}
				System.out.println(  );
				
				columnData[0] = rset.getString("氏名");
				if ( rset.getString("管理者名") == null ) {
					columnData[1] = "管理者";
				}
				else {
					columnData[1] = String.format("%s の部下", rset.getString("管理者名") );
				}
				tableItem = new TableItem(table, SWT.NONE);
				tableItem.setText(columnData);
				
			}

			stmt.close();
			con.close();

		}
		catch (Exception e) {
			 e.printStackTrace();
		}
		
		

		// 行の作成
//		TableItem tableItem = new TableItem(table, SWT.NONE);
//		data = new String[]{"山田","主任"};
//		tableItem.setText(data);
//
//		TableItem tableItem_1 = new TableItem(table, SWT.NONE);
//		data = new String[]{"鈴木","プロジェクトリーダ"};
//		tableItem_1.setText(data);


		return container;
	}

	
	// *********************************
	// ダイアログ専用のボタン
	// *********************************
	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		createButton(parent, IDialogConstants.OK_ID, IDialogConstants.OK_LABEL,
				true);
		createButton(parent, IDialogConstants.CANCEL_ID,
				IDialogConstants.CANCEL_LABEL, false);
	}

	// *********************************
	// Window サイズの初期設定
	// *********************************
	@Override
	protected Point getInitialSize() {
		// プライベート変数を使用してウインドウサイズを決定しています
		return new Point(width, height);
	}

	// *********************************
	// Window の初期位置
	// ※ デスクトップの中心
	// *********************************
	@Override
	protected Point getInitialLocation(Point initialSize) {

		GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();

		// デスクトップのサイズ
		Point windowSize = new Point(
				env.getMaximumWindowBounds().width,
				env.getMaximumWindowBounds().height);
		Point position = new Point(0,0);

		// デスクトップの中心に表示します
		return new Point(
			position.x + ((windowSize.x - width) / 2),
			position.y + ((windowSize.y - height) / 2)
		);

		/*	 親ウインドウの中心の場合 */
//		Point windowSize = this.getShell().getParent().getSize();
//		Point position = this.getShell().getParent().getLocation();
//
//		System.out.println(windowSize.x);
//
//		return new Point(
//			position.x + ((windowSize.x - width) / 2),
//			position.y + ((windowSize.y - height) / 2)
//		);

	}

}


▼ 外部ファイルの SQL 
select a.*, b.氏名 as 管理者名 from 社員マスタ a
left outer join 社員マスタ b
on a.管理者 = b.社員コード
▼ テーブルの create 文
create table `社員マスタ` (
	`社員コード` VARCHAR(4)
	,`氏名` VARCHAR(50)
	,`フリガナ` VARCHAR(50)
	,`所属` VARCHAR(4)
	,`性別` INT
	,`作成日` DATETIME
	,`更新日` DATETIME
	,`給与` INT
	,`手当` INT
	,`管理者` varchar(4)
	,`生年月日` DATETIME
	,primary key(`社員コード`)
)
関連する記事 MySQL 5.6 : テストデータ自動作成スクリプト
posted by lightbox at 2016-05-07 23:41 | java : WindowBuilder | このブログの読者になる | 更新情報をチェックする
Seesaa の各ページの表示について
Seesaa の 記事がたまに全く表示されない場合があります。その場合は、設定> 詳細設定> ブログ設定 で 最新の情報に更新の『実行ボタン』で記事やアーカイブが最新にビルドされます。

Seesaa のページで、アーカイブとタグページは要注意です。タグページはコンテンツが全く無い状態になりますし、アーカイブページも歯抜けページはコンテンツが存在しないのにページが表示されてしまいます。

また、カテゴリページもそういう意味では完全ではありません。『カテゴリID-番号』というフォーマットで表示されるページですが、実際存在するより大きな番号でも表示されてしまいます。

※ インデックスページのみ、実際の記事数を超えたページを指定しても最後のページが表示されるようです

対処としては、このようなヘルプ的な情報を固定でページの最後に表示するようにするといいでしょう。具体的には、メインの記事コンテンツの下に『自由形式』を追加し、アーカイブとカテゴリページでのみ表示するように設定し、コンテンツを用意するといいと思います。


※ エキスパートモードで表示しています

アーカイブとカテゴリページはこのように簡単に設定できますが、タグページは HTML 設定を直接変更して、以下の『タグページでのみ表示される内容』の記述方法で設定する必要があります

<% if:page_name eq 'archive' -%>
アーカイブページでのみ表示される内容
<% /if %>

<% if:page_name eq 'category' -%>
カテゴリページでのみ表示される内容
<% /if %>

<% if:page_name eq 'tag' -%>
タグページでのみ表示される内容
<% /if %>
この記述は、以下の場所で使用します
container 終わり



フリーフォントで簡単ロゴ作成
フリーフォントでボタン素材作成
フリーフォントで吹き出し画像作成
フリーフォントではんこ画像作成
ほぼ自由に利用できるフリーフォント
フリーフォントの書体見本とサンプル
画像を大きく見る為のウインドウを開くボタンの作成

CSS ドロップシャドウの参考デモ
イラストAC
ぱくたそ
写真素材 足成
フリーフォント一覧
utf8 文字ツール
右サイド 終わり
base 終わり