SoftwareEngineering

サンプル集

画面制御

親ウィンドウを取得する

/**
 * container を乗せている親ウィンドウを取得します。
 * 作成日 : (2012/09/04 14:44:37)
 * @param component java.awt.container
 */
private Window getParentWindow(Container container) {
    
    debugPrint("------------------------------------------------------------");
    debugPrint("-- 親ウィンドウを検索");
    debugPrint("------------------------------------------------------------");
    Container parentContainer = container.getParent();
    while (parentContainer != null) {
        debugPrint("parentContainer.getClass.getSuperclass().getName", parentContainer.getClass().getSuperclass().getName());
        debugPrint("parentContainer.getClass.getName", parentContainer.getClass().getName());
        debugPrint("parentContainer.getName", parentContainer.getName());
        
        if (parentContainer instanceof Window) return (Window)parentContainer;
        
        debugPrint("------------------------------------------------------------");
        parentContainer = parentContainer.getParent();
    }
    
    return null;
}

ツールヒントに表示するテキストを登録

/**
 * ツールヒントに表示するテキストを登録します
 *  テキストが空文字だと「・」が表示されるので、null に置き換えて登録します
 * 作成日 : (2013/04/12 10:18:07)
 * @param component javax.swing.JComponent
 * @param text java.lang.String
 */
private void setToolTipText(JComponent component, String text) {
    if (component == null) return;
    
    if (text == null) {
        component.setToolTipText(null);
    } else if (text.equals("")) {
        component.setToolTipText(null);
    } else {
        component.setToolTipText(text);
    }
}

文字列処理

NULL 値の置き換え

String nullToEmpty(String value)

/**
 * value が NULL 値であれば空文字を戻します
 * 作成日 : (2013/06/04 9:31:48)
 * @return java.lang.String
 * @param value java.lang.String
 */
private String nullToEmpty(String value) {
   if (value != null) return value;
   return "";
}

数値変換

int strToIntDef(String, int)

/**
 * 文字列 value を int型に変換して戻す。
 *  文字列 value がint型に変換できない場合は、defaultValue を戻す。
 * 作成日 : (2011/11/21 13:17:17)
 * @return int
 * @param value java.lang.String
 * @param defaultValue int
 */
private int strToIntDef(String value, int defaultValue) {
   int result = defaultValue;
   
   try {
       result = Integer.parseInt(value);
   } catch (Exception e) {
       result = defaultValue;
   }
   
   return result;
}

long strToLongDef(String, long)

/**
 * 文字列 value を long型に変換して戻す。
 *  文字列 value がlong型に変換できない場合は、defaultValue を戻す。
 * 作成日 : (2011/07/29 13:39:13)
 * @return long
 * @param value java.lang.String
 * @param defaultValue long
 */
private long strToLongDef(String value, long defaultValue) {
   long result = defaultValue;
   
   try {
       result = Long.parseLong(value);
   } catch (Exception e) {
       result = defaultValue;
   }
   
   return result;
}

スレッド

サブスレッドが停止するまで待つ

イベントディスパッチスレッドに制御を任せる

Swing はスレッドに対して安全ではありません。 イベントディスパッチスレッド以外のスレッド上で Swing にアクセスしない。 サブスレッドが開始している状態で終了ボタンをクリックすると、終了処理された後にイベントディスパッチスレッドに制御を任せた処理が実行される可能性があります。 (終了ボタンのクリックイベントはイベントディスパッチスレッドで実行されるため)

CSV

CSVを読み込む

CSVを書きこむ

XML

XMLを読み込む

絶対ロケーションパスを取得する

ファイル名から拡張子を除いたベース名を取得する

プロパティファイル

XML版

配列

String配列

歯抜けになっている中身を前詰する

public class RemoveBlankItems{
    
    public static void main(String args[]) throws Exception {
        String items[] = new String[30];
        
        for (int i = 0; i < items.length; i++) {
            items[i] = "";
        }
        
        items[5] = "5番目のデータ";
        items[10] = "10番目のデータ";
        items[15] = "15番目のデータ";
        items[20] = "20番目のデータ";
        items[25] = "25番目のデータ";
        
        System.out.println("---------------------------------------------------------------------------");
        System.out.println("-- 未処理");
        for (int i = 0; i < items.length; i++) {
            System.out.println("items[" + Integer.toString(i) + "]:[" + items[i] + "]");
        }
        
        removeBlankItems(items);
        
        System.out.println("---------------------------------------------------------------------------");
        System.out.println("-- 処理後");
        for (int i = 0; i < items.length; i++) {
            System.out.println("items[" + Integer.toString(i) + "]:[" + items[i] + "]");
        }
    }
    
    
    private static void removeBlankItems(String items[]) {
        String buffer[] = new String[items.length];
        
        // 配列の中身を退避
        for (int index = 0; index < items.length; index++) {
            buffer[index] = items[index];
        }
        
        // 前方に詰めたい配列の中身をクリア
        for (int index = 0; index < items.length; index++) {
            items[index] = "";
        }
        
        // 前方に詰める
        int itemIndex = 0;
        for (int bufferIndex = 0; bufferIndex < buffer.length; bufferIndex++) {
            if (buffer[bufferIndex] == null) continue;
            if (buffer[bufferIndex].equals("")) continue;
            
            items[itemIndex] = buffer[bufferIndex];
            itemIndex++;
        }
        
    }
    
}

画像

画像を回転させる

private Image rotate(Image sourceImage, int rotation) {
    int sourceWidth = sourceImage.getWidth(this);       // 幅(変換前の画像)
    int sourceHeight = sourceImage.getHeight(this);     // 高さ(変換後の画像)
    double angle = 0;                                   // 角度
    
    int targetWidth = sourceWidth;                      // 幅(変換後の画像)
    int targetHeight = sourceHeight;                    // 高さ(変換後の画像)
    
    double posX = 0;    // 中心点 X座標
    double posY = 0;    // 中心点 Y座標
    
    
    switch (rotation) {
        case 1: {
            // 右に90度回転する
            angle = Math.toRadians(90d);
            posX = (sourceWidth / 2) - ((sourceWidth - sourceHeight) / 2);
            posY = sourceHeight / 2;
            
            targetWidth = sourceHeight;
            targetHeight = sourceWidth;
            
            break;
        }
        
        case 2: {
            // 右に180度回転する
            angle = Math.toRadians(180d);
            posX = sourceWidth / 2;
            posY = sourceHeight / 2;
            
            targetWidth = sourceWidth;
            targetHeight = sourceHeight;
            
            break;
        }
        
        case 3: {
            // 右に270度回転する
            angle = Math.toRadians(270d);
            posX = sourceWidth / 2;
            posY = (sourceHeight / 2) + ((sourceWidth - sourceHeight) / 2);
            
            targetWidth = sourceHeight;
            targetHeight = sourceWidth;
            
            break;
        }
    }
    
    
    BufferedImage targetImage = new BufferedImage(targetWidth, targetHeight, BufferedImage.TYPE_INT_RGB);
    
    java.awt.geom.AffineTransform affin
        = java.awt.geom.AffineTransform.getRotateInstance(angle, posX, posY);
    
    Graphics2D g2 = (Graphics2D)targetImage.createGraphics();
    g2.drawImage(sourceImage, affin, null);
    
    return targetImage;
}

印刷処理(JDK 1.3)

ページの印刷方向に初期値を設定する方法

印刷ジョブのプロパティを変更するためのダイアログにページの印刷方向に初期値を設定する方法を以下に示します。 ダイアログで指定した印刷方向でページが印刷されます。

コード

import java.awt.*;
import java.awt.print.*;

public class DefaultOrientation implements Printable {
    private static Font fnt = new Font("Helvetica",Font.PLAIN,24);
    
    
    
    public static void main(String[] args) {
        PrinterJob job = PrinterJob.getPrinterJob();
        
        
        PageFormat defaultPage = job.defaultPage();
        defaultPage.setOrientation(PageFormat.LANDSCAPE);
        job.setPrintable(new DefaultOrientation(), defaultPage);    // Point-1
        
        
        if (job.printDialog()) {
            
            try {
                job.print();
            } catch (PrinterException e) {
                e.printStackTrace();
            }
            
        }
        
    }
    
    
    
    public int print(Graphics g, PageFormat pf, int pageIndex) throws PrinterException {
        if (5 <= pageIndex) return Printable.NO_SUCH_PAGE;
        
        g.setFont(fnt);
        g.setColor(Color.green);
        g.drawString("Page " + (pageIndex+1), 100, 100);
        
        return Printable.PAGE_EXISTS;
    }
    
}

実行結果

DefaultOrientation_0001.PNG

解説

注意事項/連絡事項

参考サイト

デバッグ用メソッド

事前準備

デバッグ用のメソッドを使用するには下記の定数を定義しておく必要がある。

private final boolean DEBUG_TRACE_ON = true;/* デバック出力する場合は true をセットする */

デバッグ出力

void debugPrint(String)

/**
 * デバッグ用出力
 * 作成日 : (2011/07/12 13:36:31)
 * @param value java.lang.String
 */
private void debugPrint(String value) {
    if (!DEBUG_TRACE_ON) return;
    
    System.out.println(value);
}

void debugPrint(String[])

/**
 * デバッグ用出力
 * 作成日 : (2011/01/14 10:21:24)
 * @param values java.lang.String[]
 */
private void debugPrint(String[] values) {
   if (!DEBUG_TRACE_ON) return;
        
   for (int index = 0; index < values.length; index++) {
       if (0 < index) System.out.print(",");
       System.out.print(values[index]);
   }
   System.out.print("\r\n");
}

void debugPrint(String, String)

/**
 * デバッグ用出力
 * 作成日 : (2011/02/15 10:06:48)
 * @param keyword java.lang.String
 * @param value java.lang.String
 */
private void debugPrint(String keyword, String value) {
   if (!DEBUG_TRACE_ON) return;
        
   System.out.println(keyword + ":[" + value + "]");
}

void debugPrintTd(String)

/**
 * インターフェースにセットされている値を出力する
 * 作成日 : (2011/06/01 14:43:22)
 * @param keyword java.lang.String
 */
private void debugPrintTd(String keyword) {
   if (!DEBUG_TRACE_ON) return;
       
   System.out.println("------------------------------------------------------------");
   System.out.println("-- " + keyword + " START");
   System.out.println("------------------------------------------------------------");
   
   
   System.out.println("------------------------------------------------------------");
   System.out.println("-- " + keyword + " END");
   System.out.println("------------------------------------------------------------");
}
debugPrintTd("Java >> COBOL");	// デバッグ用ロジック
debugPrintTd("COBOL >> Java");	// デバッグ用ロジック

void debugPrintDataTable(String)

/**
 * デバック用
 *  メモリ内の入力データを出力する
 * 作成日 : (2011/08/29 9:35:25)
 */
private void debugPrintDataTable(String keyword) {
   if (!DEBUG_TRACE_ON) return;
   
   System.out.println("------------------------------------------------------------");
   System.out.println("-- " + keyword + "DataTable START");
   System.out.println("------------------------------------------------------------");
   
   debugPrint("データ件数", Integer.toString(dataTable.size()));
   
   for (int index = 0; index < dataTable.size(); index++) {
       DataRow dataRow = (DataRow)dataTable.get(index);
       
       debugPrint(new String[] {
            index + "番目"
           ,dataRow.toString()
       });
   }
   
   System.out.println("------------------------------------------------------------");
   System.out.println("-- " + keyword + "DataTable END");
   System.out.println("------------------------------------------------------------");
}

void debugPrintTabOrder(JComponent, int)

/**
 * デバッグ用出力
 *  タブ移動順序を出力する
 * 作成日 : (2011/06/10 9:12:44)
 * @param firstComponent javax.swing.JComponent 
 * @param upperBound int 無限ループを回避するために使用
 */
private void debugPrintTabOrder(JComponent firstComponent, int upperBound) {
   if (!DEBUG_TRACE_ON) return;
   if (firstComponent == null) return;

   
   System.out.println("------------------------------------------------------------");
   System.out.println("-- タブ移動順序 START");
   System.out.println("------------------------------------------------------------");
   System.out.println("移動順序,オブジェクト名");

   
   int index = 0;
   JComponent targetComponent = firstComponent;
   while (true) {
       
       debugPrint(new String[] {
            index + "番目"
           ,targetComponent.getName()
       });


       targetComponent = (JComponent)targetComponent.getNextFocusableComponent();		
       index++;

           
       if (upperBound < index) break;
       if (targetComponent == null) break;
       if (targetComponent.equals(firstComponent)) break;
   }

   
   System.out.println("------------------------------------------------------------");
   System.out.println("-- タブ移動順序 END");
   System.out.println("------------------------------------------------------------");
}

void debugPrintTime(String)

/**
 * デバック用
 *  1970年1月1日午前0時からの経過時間をミリ秒で出力する
 * 作成日 : (2012/05/07 11:52:08)
 * @param s java.lang.String
 */
private void debugPrintTime(String value) {
   if (!DEBUG_TRACE_ON) return;
   
   debugPrint(value, Long.toString((new Date()).getTime()));
}

トップ   一覧 検索 最終更新   ヘルプ   最終更新のRSS