ログインしてさらにmixiを楽しもう

コメントを投稿して情報交換!
更新通知を受け取って、最新情報をゲット!

ひろ☆みんを崇める会!コミュの今後のJAVA

  • mixiチェック
  • このエントリーをはてなブックマークに追加

コメント(30)

メニューバーの実装

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

class JMenuSample01 extends JFrame
{
MyLabel lbl;
JTextField txt;
public JMenuSample01()
{
super( "sample" );
setDefaultCloseOperation( EXIT_ON_CLOSE );
Dimension scr = Toolkit.getDefaultToolkit().getScreenSize();
int w = scr.width;
int h = scr.height;
setBounds( w / 4 , h / 4 , w / 4 , h / 5 );
JPanel panel = ( JPanel )getContentPane();
panel.setLayout( new FlowLayout() );
lbl = new MyLabel( "" , new Dimension( 100,50 ) );
lbl.setBackground( Color.green );

txt = new JTextField( 10 );

panel.add( lbl );
panel.add( new JButton( new FileSaveAction() ) );
panel.add( new JButton( new FileOpenAction() ) );
panel.add( new JButton( new ClearAction() ) ) ;
panel.add( txt );

setVisible( true );

JMenuItem fileMenuOpen = new JMenuItem( new FileOpenAction() );
JMenuItem fileMenuSave = new JMenuItem( new FileSaveAction() );
JMenu menuFile = new JMenu( "ファイル" );
menuFile.add(fileMenuOpen);
menuFile.add(fileMenuSave);

JMenuItem fileMenuClear = new JMenuItem( new ClearAction() );
JMenu menuEdit = new JMenu( "編集" );
menuEdit.add(fileMenuClear);

JMenuBar menu = new JMenuBar();

menu.add(menuFile);
menu.add(menuEdit);

setJMenuBar(menu);
}
public static void main( String[] arg )
{
new JMenuSample01();
}

class FileSaveAction extends AbstractAction
{
public FileSaveAction()
{
putValue( Action.NAME , "保存" );
}
public void actionPerformed( ActionEvent e )
{
try
{
MyFile mf = new MyFile();
mf.setFilePath("test.txt");
mf.fileSave( txt.getText() );
}
catch( IOException ex )
{
System.out.println( "error" );
}
}
}
class FileOpenAction extends AbstractAction
{
public FileOpenAction()
{
putValue( Action.NAME , "開く" );
}
public void actionPerformed( ActionEvent e )
{
try
{
MyFile mf = new MyFile();
mf.setFilePath( "test.txt" );
String dat = mf.fileRead();
if( dat != null )
{
lbl.setText( dat );
}
}
catch( IOException ex )
{
lbl.setText( "error" );
}
}
}
class ClearAction extends AbstractAction
{
public ClearAction()
{
putValue( Action.NAME , "クリア" );
}
public void actionPerformed( ActionEvent e )
{
txt.setText("");
lbl.setText("");
}
}
}

class MyLabel extends JLabel
{
public MyLabel( String title )
{
super( title );
}
public MyLabel( String title , Dimension size )
{
super( title );
setPreferredSize( size );
}
public MyLabel( String title ,int w , int h )
{
super( title );
setPreferredSize(new Dimension( w , h ) );
}
public void setBackground( Color color )
{
setOpaque( true );
super.setBackground( color );
}
}

class MyFile
{
private String filePath;

public MyFile()
{
;
}

public void setFilePath( String filePath )
{
this.filePath = filePath;
}

public String getFilePath()
{
return filePath ;
}

public void fileSave( String dat ) throws IOException
{
BufferedWriter bw = new BufferedWriter( new FileWriter( filePath ) );

bw.write( dat ) ;
bw.newLine() ;
bw.close() ;
}

public String fileRead() throws IOException
{
BufferedReader br = new BufferedReader( new FileReader( filePath ) );

String str = br.readLine();

br.close();

return str;
}
}

/*
メニューの実装用クラス
 JMenuBar メニューとして表示される行
Jmenu 各ブロック(ファイルや編集)
JMenuItem ここの選択項目(ファイルの 新規、開く)

利用の考え方
JMenuItemを1つ以上 JMenuに登録 (開く → ファイル)
JMenuに1つ以上   JMenuBarに登録 (ファイルMenu → )
JMenuBarを  JFrameにセット ()

開く用の選択項目
JMenuItem fileMenuOpenを生成
JMenuItemの生成は
ボタンなら
new JButton( new FileOpenAcyion() );

new JMenuItem( 対象アクション );
new JMenuItem( new FileOpenAcyion() );

JMenuItem fileMenuOpen
= new JMenuItem( new FileOpenAction() );

ファイル メニュー
JMenuの生成は new JMenu( 表示文字列);
JMenu menuFile = new JMenu( "ファイル");

先ほどの fileMenuOpen項目を登録
JMenu参照変数.add( 対象の項目 )

メニューバーの生成
JMenuBar menuBar = new JMenuBar();
先ほどの menuFileを登録
menuBar.add( menuFile );

メニューバーを見えるようにする → JFrameにセット
JFrameのsetJMenuBar(対象); メソッドを利用

*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

class JMenuSample01 extends JFrame
{
/* ----------------------省略--------------------------- */
    
JMenuItem fileMenuOpen = new JMenuItem( new FileOpenAction() );
JMenuItem fileMenuSave = new JMenuItem( new FileSaveAction() );
JMenuItem end = new JMenuItem( new CloseAction() );
JMenu menuFile = new JMenu( "ファイル" );
menuFile.add(fileMenuOpen);
menuFile.add(fileMenuSave);
menuFile.addSeparator();
menuFile.add(end);

JMenuItem fileMenuClear = new JMenuItem( new ClearAction() );
JMenu menuEdit = new JMenu( "編集" );
menuEdit.add(fileMenuClear);

JMenuBar menuBar = new JMenuBar();

menuBar.add(menuFile);
menuBar.add(menuEdit);

setJMenuBar(menuBar);

setVisible( true );
}
public static void main( String[] arg )
{
new JMenuSample01();
}

class CloseAction extends AbstractAction
{
public CloseAction()
{
putValue( Action.NAME , "閉じる" );
}
public void actionPerformed( ActionEvent e )
{
System.exit(0);
}
}
}
JFileChooser

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

class JFileChooser01 extends JFrame
{
private JTextField txt;
JPanel panel;
public JFileChooser01()
{
super( "sample" );
setDefaultCloseOperation( EXIT_ON_CLOSE );
Dimension scr = Toolkit.getDefaultToolkit().getScreenSize();
int w = scr.width;
int h = scr.height;
setBounds( w / 4 , h / 4 , w / 4 , h / 5 );

panel = ( JPanel )getContentPane();

txt = new JTextField(20);
panel.setLayout( new BorderLayout() );

panel.add( txt , BorderLayout.NORTH);
panel.add( new JButton( new DispAction() ) , BorderLayout.CENTER );

setVisible( true );
}
public static void main( String[] arg )
{
new JFileChooser01();
}

class DispAction extends AbstractAction
{
public DispAction()
{
putValue( Action.NAME , "表示" );
}
public void actionPerformed( ActionEvent e )
{
JFileChooser jfc = new JFileChooser();
int r = jfc.showOpenDialog(null);
}
}
}

class MyLabel extends JLabel
{
public MyLabel( String title )
{
super( title );
}
public MyLabel( String title , Dimension size )
{
super( title );
setPreferredSize( size );
}
public MyLabel( String title ,int w , int h )
{
super( title );
setPreferredSize(new Dimension( w , h ) );
}
public void setBackground( Color color )
{
setOpaque( true );
super.setBackground( color );
}
}


/*JFileChooserを開くモードで表示
*public int showOpenDialog(Component parent)を利用
* 定義より showOpenDialogメソッドは インスタンスメソッド
* 定義に static がない(クラスメソッドではない)
* => JFileChooserのオブジェクト生成が必要
* 例)
* JFileChooser jfc = new JFileChooser();
* int r = jfc.showOpenDialog(null);
*/
//JFileChooser01

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

class JFileChooser01 extends JFrame
{
private JTextField txt;
JPanel panel;
public JFileChooser01()
{
super( "sample" );
setDefaultCloseOperation( EXIT_ON_CLOSE );
Dimension scr = Toolkit.getDefaultToolkit().getScreenSize();
int w = scr.width;
int h = scr.height;
setBounds( w / 4 , h / 4 , w / 4 , h / 5 );

panel = ( JPanel )getContentPane();

txt = new JTextField(20);
panel.setLayout( new BorderLayout() );

panel.add( txt , BorderLayout.NORTH);
panel.add( new JButton( new DispAction() ) , BorderLayout.CENTER );

setVisible( true );
}
public static void main( String[] arg )
{
new JFileChooser01();
}

class DispAction extends AbstractAction
{
public DispAction()
{
putValue( Action.NAME , "表示" );
}
public void actionPerformed( ActionEvent e )
{
JFileChooser jfc = new JFileChooser();
int r = jfc.showOpenDialog(null);
}
}
}

class MyLabel extends JLabel
{
public MyLabel( String title )
{
super( title );
}
public MyLabel( String title , Dimension size )
{
super( title );
setPreferredSize( size );
}
public MyLabel( String title ,int w , int h )
{
super( title );
setPreferredSize(new Dimension( w , h ) );
}
public void setBackground( Color color )
{
setOpaque( true );
super.setBackground( color );
}
}
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;

class FileMenuEnsyu extends JFrame
{
String filePath = "";
JTextField txt;
public FileMenuEnsyu()
{
super( "sample" );
setDefaultCloseOperation( EXIT_ON_CLOSE );
Dimension scr = Toolkit.getDefaultToolkit().getScreenSize();
int w = scr.width;
int h = scr.height;
setBounds( w / 4 , h / 4 , w / 4 , h / 5 );
JPanel panel = ( JPanel )getContentPane();
panel.setLayout( new FlowLayout() );

txt = new JTextField( 10 );

panel.add( txt );

JMenuItem newOpen = new JMenuItem( new NewAction() );
JMenuItem fileMenuOpen = new JMenuItem( new FileOpenAction() );
JMenuItem fileOverWrite = new JMenuItem( new FileOverWriteAction() );
JMenuItem fileMenuSave = new JMenuItem( new FileSaveAction() );
JMenuItem end = new JMenuItem( new CloseAction() );
JMenu menuFile = new JMenu( "ファイル" );
menuFile.add(newOpen);
menuFile.add(fileMenuOpen);
menuFile.add(fileOverWrite);
menuFile.add(fileMenuSave);
menuFile.addSeparator();
menuFile.add(end);

JMenuBar menuBar = new JMenuBar();

menuBar.add(menuFile);

setJMenuBar(menuBar);

setVisible( true );
}
public static void main( String[] arg )
{
new FileMenuEnsyu();
}

class FileSaveAction extends AbstractAction
{
public FileSaveAction()
{
putValue( Action.NAME , "名前を付けて保存" );
}
public void actionPerformed( ActionEvent e )
{

ExampleFileFilter filter = new ExampleFileFilter();
JFileChooser jfc = new JFileChooser();
jfc.setFileFilter( filter );
int r = jfc.showSaveDialog( null );


try
{
if( r == JFileChooser.APPROVE_OPTION )
{
filePath = jfc.getSelectedFile().toString();
MyFile mf = new MyFile();
mf.setFilePath( filePath );
mf.fileSave( txt.getText() );
}
}
catch( IOException ex )
{
System.out.println( "error" );
}
}
}
class FileOpenAction extends AbstractAction
{
public FileOpenAction()
{
putValue( Action.NAME , "開く" );
}
public void actionPerformed( ActionEvent e )
{

ExampleFileFilter filter = new ExampleFileFilter();
JFileChooser jfc = new JFileChooser();
jfc.setFileFilter( filter );
int r = jfc.showOpenDialog( null );

try
{
if( r == JFileChooser.APPROVE_OPTION )
{
filePath = jfc.getSelectedFile().toString();
MyFile mf = new MyFile();
mf.setFilePath( filePath );
String dat = mf.fileRead();
if( dat != null )
{
txt.setText( dat );
}
}
}
catch( IOException ex )
{
System.out.println( "error" );
}
}
}

class FileOverWriteAction extends AbstractAction
{
public FileOverWriteAction()
{
putValue( Action.NAME , "上書き保存" );
}
public void actionPerformed( ActionEvent e )
{

ExampleFileFilter filter = new ExampleFileFilter();
JFileChooser jfc = new JFileChooser();
jfc.setFileFilter( filter );
try
{
if( filePath == "")
{
int r = jfc.showSaveDialog( null );

if( r == JFileChooser.APPROVE_OPTION )
{
filePath = jfc.getSelectedFile().getName();
MyFile mf = new MyFile();
mf.setFilePath( filePath );
mf.fileSave( txt.getText() );
}
}
else
{
MyFile mf = new MyFile();
mf.setFilePath( filePath );
mf.fileSave( txt.getText() );
}
}
catch( IOException ex )
{
System.out.println( "error" );
}
}
}

class NewAction extends AbstractAction
{
public NewAction()
{
putValue( Action.NAME , "新規" );
}
public void actionPerformed( ActionEvent e )
{
txt.setText("");
filePath = "";
}
}
//続き

class CloseAction extends AbstractAction
{
public CloseAction()
{
putValue( Action.NAME , "閉じる" );
}
public void actionPerformed( ActionEvent e )
{
System.exit(0);
}
}
}

class MyLabel extends JLabel
{
public MyLabel( String title )
{
super( title );
}
public MyLabel( String title , Dimension size )
{
super( title );
setPreferredSize( size );
}
public MyLabel( String title ,int w , int h )
{
super( title );
setPreferredSize(new Dimension( w , h ) );
}
public void setBackground( Color color )
{
setOpaque( true );
super.setBackground( color );
}
}

class MyFile
{
private String filePath;

public MyFile()
{
;
}

public void setFilePath( String filePath )
{
this.filePath = filePath;
}

public String getFilePath()
{
return filePath ;
}

public void fileSave( String dat ) throws IOException
{
BufferedWriter bw = new BufferedWriter( new FileWriter( filePath ) );

bw.write( dat ) ;
bw.newLine() ;
bw.close() ;
}

public String fileRead() throws IOException
{
BufferedReader br = new BufferedReader( new FileReader( filePath ) );

String str = br.readLine();

br.close();

return str;
}
}
import java.util.*;

class ArrayListSample
{
public static void main (String[] args)
{
ArrayList<String> lst = new ArrayList<String>();

Scanner keyIn = new Scanner(System.in);
String dat ;

while( keyIn.hasNext() )
{
dat = keyIn.next();
lst.add(dat);
}
for( int i = 0 ; i < lst.size() ; i++ )
{
System.out.println( lst.get(i) );
}
}
}

/*
* Genericsより ArrayList<型>クラスを利用
* キーb−どより 複数のStringデータを入力
* CTLR+Zの後で 入力したデータを表示
*
* 手順? Stringを扱うArrayListの宣言
* ArrayList<String> lst ←変数lstを宣言
* = new ArrayList<String>();←生成
* 手順? キーボードよりStringを入力するために
* Sccanner keyIn = new Scanner(System.in);
* String dat ;
* 手順? CTRL+Zまで入力とArrayListへの登録
* while( keyIn.hasNext() )
* {
* dat = keyIn.next();
* lst.add(dat); ← 登録
* }
* 手順? ArrayListに登録されたデータの表示
* 登録件数分の繰り返しと表示
* for( int i = 0 ; i < lst.size() ; i++ )
* i番目のデータを取り出す
* lst.get(i);
*
* ヘルプより
* ArrayListを参照
* パッケージは
* ArrayListはクラス→オブジェクトを生成し、
* メソッドでデータを扱う
* 用意されてアイルメソッドは?
* データの登録 → add
* データの取り出し → get
* 登録件数の取り出し→ size
* ArrayListは動的に扱える(要素数が不定)
*
* 特定の型やオブジェクトを複数件扱うとき、
* ArrayListを利用
* 補足
* Javaの場合、Vectorクラスなどのほかの方法もある
*/
import java.util.*;
import java.io.*;
import java.net.*;

class Client03
{
public static void main (String[] args)
{
ArrayList<String> lst = new ArrayList<String>();

Scanner keyIn = new Scanner(System.in);
String dat ;

while( keyIn.hasNext() ) //CTRL+Zが押されるまで
{
dat = keyIn.next(); //ArrayList入力
lst.add(dat) ; //Listに登録
}

try
{
InetAddress host = InetAddress.getByName("PC16");
Socket soc = new Socket( host , 50000 );

OutputStream out = soc.getOutputStream( );
OutputStreamWriter osw = new OutputStreamWriter( out );
BufferedWriter bw = new BufferedWriter( osw );
for( int i = 0 ; i < lst.size() ; i++ )
{
bw.write( lst.get(i) );
bw.newLine( );
bw.flush( );
}

bw.write( 'E' );
bw.newLine( );
bw.close( );
soc.close( );

}
import java.util.*;
import java.io.*;
import java.net.*;

class Server03
{
public static void main (String[] args)
{
try
{
ServerSocket svr = new ServerSocket( 50000 );
Socket soc = svr.accept( );

InputStream in = soc.getInputStream( );
InputStreamReader isr = new InputStreamReader( in );
BufferedReader br = new BufferedReader( isr );

String dat = br.readLine( );
while( !dat.equals( "E" ) )
{
System.out.println( dat );
dat = br.readLine( );
}

br.close( );
soc.close( );
svr.close( );
}
catch( IOException ex )
{
;
}

}
}
import java.util.*;
import java.net.*;
import java.io.*;

class Client05
{
public static void main(String [] args)
{
ArrayList<String> lst = new ArrayList<String>();

Scanner keyIn = new Scanner(System.in);
String dat ;

while( keyIn.hasNext() )
{
dat = keyIn.next();
lst.add(dat) ;
}

try
{
InetAddress host = InetAddress.getByName("pc16");
;
Socket soc = null;
for( int i = 0 ; i < 3 && soc == null ; i++)
{
try
{
soc= new Socket(host, 50000);
Thread.sleep(1000);
}
catch(IOException ex)
{
}
catch(InterruptedException ex)
{
}
}
if( soc != null){
try{
OutputStream out= soc.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter( out );
BufferedWriter bw = new BufferedWriter( osw );

for( int i = 0 ; i < lst.size() ; i++ )
{
bw.write( lst.get(i) );
bw.newLine( );
bw.flush( );
}

bw.close( );
soc.close( );
}
catch(IOException e)//new Socket
{
System.out.println( "対象に接続できない" );
}

}
}
catch(UnknownHostException e)//InetAddress.getByName
{
System.out.println( "対象PCが見つからない" );
}

}
}

import java.io.*;
import java.net.*;
class Server05
{
public static void main(String [] args)
{
ServerSocket svr= null;
Socket soc ;
try
{
svr = new ServerSocket(50000);
while(true)
{
soc = svr.accept( );
InputStream in = soc.getInputStream( );
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader( isr );

String dat = br.readLine( );
while( dat != null )
{
System.out.println( dat );
dat = br.readLine( );
}
br.close( );
soc.close();
}
}
catch(IOException e){
}
finally
{
if( svr != null){
try
{
svr.close();
}
catch(IOException e){
}
}
}
}
}
public class ThreadSamp01
{
public static void main(String[] args)
{
ThreadSub tSub = new ThreadSub();
tSub.start();

try
{
for (int i = 0; i < 5; i++)
{
System.out.println("main : " + i);
Thread.sleep(200);
}
}
catch(InterruptedException e)
{
;
}
finally
{
System.out.println("main end!!");
}
}
}
class ThreadSub extends Thread
{
public void run()
{
try
{
for(int i = 0 ; i < 5 ; i++)
{
System.out.println("Sub : " + i);
Thread.sleep(500);
}
}
catch(InterruptedException e)
{
;
}
finally
{
System.out.println("main end!!");
}
}
}

/*
* プログラム内の処理は、原則シングルスレッド
* 記述順に処理されている
* ThreadSub tSub = new ThreadSub();
* tSub.run(); <-Subの表示
* 次にmain側の表示
* for (int i = 0; i < 5; i++)
* {
* System.out.println("main : " + i);
* }
* Windowsなどでは 平行(同時)して2つ以上の処理を
* 実行する場合がある
* 処理画面に、現在の時間を常時表示
* 例)C#では Timerを利用して表示していた
* Form上の処理を平行してTimerの処理を実行
* =>マルチスレッドと呼ぶ
*
* Javaはマルチスレッドをサポートしている
* -> Threadクラスを利用
* =>標準で利用できる(import不要)
*
* ThreadSubSamp01の改良
* ThreadSubクラス -> Thread用に指定
* -> Threadを継承指定
* ______________
* class ThreadSub extends Thread
* { ~~~~~~~~~~~~~~
* public void run()
* {
* for(int i = 0 ; i < 5 ; i++)
* {
* System.out.println("Sub : " + i);
* }
* System.out.println("sub end!!");
* }
* }
* 注意 : マルチスレッドの実行は
* Start( )メソッドで
* ThreadSub tSub = new ThreadSub();
* tSub.run(); -> tSub.start();
* ~~~~~~~~~~~~~
* start()メソッドの実行すると
* 対象のThreadクラスのrun()メソッドが呼ばれる
*
* 処理タイミングを合わせるために
* sleepメソッドを追加
* main側 Thread.sleep(200);
* sub側 Thread.sleep(500);
* 注意 try catchが必要 -> コンパイルで確認
*
* Threadクラス継承以外の奉納
* クラス継承は javaでは 1対1
* 他のクラスも継承指定の場合
* Threadクラスの代わりに
* Runnableインタフェースを利用
*/
public class ThreadSamp03
{
public static void main(String[] args)
{
ThreadSub1 tSub1 = new ThreadSub1();
ThreadSub2 tSub2 = new ThreadSub2();
tSub1.setPriority(Thread.MAX_PRIORITY);
tSub2.setPriority(Thread.MIN_PRIORITY);
tSub1.start();
tSub2.start();
System.out.println("main end!!");
}
}
class ThreadSub1 extends Thread
{
public void run()
{
try
{
for(int i = 0 ; i < 5 ; i++)
{
System.out.println("Sub1 : " + i);
Thread.sleep(500);
}
}
catch(InterruptedException e)
{
;
}
finally
{
System.out.println("sub1 end!!");
}
}
}
class ThreadSub2 extends Thread
{
public void run()
{
try
{
for(int i = 0 ; i < 5 ; i++)
{
System.out.println("Sub2 : " + i);
Thread.sleep(300);
}
}
catch(InterruptedException e)
{
;
}
finally
{
System.out.println("sub2 end!!");
}
}
}
/*
* マルチスレッドの処理の注意
* 1.複数スレッドの処理順番
* 今回の例でも 実行ごとにタイミングが異なる
* ->Thread用クラスに優先順位を指定できる
* ____________
* =>同時タイミングのときに先に実行する指定
* ->優先順位の高いほうが先
* 優先順位は 1(低)〜10(高)
* Threadクラスのフィールド名
* Thread.MIN_PRIORITY -> 1
* Thread.MAX_PRIORITY -> 10
* Thread.NORMAL_PRIORITY -> 5
* 優先順位の指定のために改良
* クラス変更
* ThreadSub -> ThreadSub1
* ThreadSub2クラスを追加
*
* main側
* ThreadSub1生成
* ThreadSub2生成
* ThreadSub1実行
* ThreadSub2実行
* System.out.println("main end!!");
* for文を削除
* 実行前に 優先順位を指定
* setPriorityメソッドを利用
*
* ThreadSub1 tSub1 = new ThreadSub1();
* ThreadSub2 tSub2 = new ThreadSub2();
* tSub1.setPriority(Thread.MAX_PRIORITY);
* tSub2.setPriority(Thread.MIN_PRIORITY);
* tSub1.start();
* tSub2.start();
*/
public class ThreadSamp04
{
public static void main(String[] args)
{
ThreadSub1 tSub1 = new ThreadSub1();
ThreadSub2 tSub2 = new ThreadSub2();
tSub1.setPriority(Thread.MAX_PRIORITY);
tSub2.setPriority(Thread.MIN_PRIORITY);
tSub1.start();
tSub2.start();
try
{
tSub1.join();
tSub2.join();
}
catch(InterruptedException e)
{
;
}

System.out.println("main end!!");
}
}
class ThreadSub1 extends Thread
{
public void run()
{
try
{
for(int i = 0 ; i < 5 ; i++)
{
System.out.println("Sub1 : " + i);
Thread.sleep(500);
}
}
catch(InterruptedException e)
{
;
}
finally
{
System.out.println("sub1 end!!");
}
}
}
class ThreadSub2 extends Thread
{
public void run()
{
try
{
for(int i = 0 ; i < 5 ; i++)
{
System.out.println("Sub2 : " + i);
Thread.sleep(300);
}
}
catch(InterruptedException e)
{
;
}
finally
{
System.out.println("sub2 end!!");
}
}
}

/*
* マルチスレッドの処理の注意
* 2.複数スレッドの処理は平行
* 今回の例でも 先にmainが終わる?
* 本来 mainが全体の処理
*
* Thread用処理が終わるのを待つことができる
* イメージ
* 2つのThreadが終わったら
* System.out.println("main end");
* を実行し、mainを終了
* Thread用処理が終わるのを待つ
* =>join()メソッド
* 注意 InterruptedExceptionのcatch
*/
public class ThreadSamp05
{
public static void main(String[] args)
{
Cnt cnt = new Cnt(); //共有資源
ThreadSub1 tSub1 = new ThreadSub1(cnt);
ThreadSub2 tSub2 = new ThreadSub2(cnt);
tSub1.setPriority(Thread.MAX_PRIORITY);
tSub2.setPriority(Thread.MIN_PRIORITY);
tSub1.start();
tSub2.start();
try
{
tSub1.join();
tSub2.join();
}
catch(InterruptedException e)
{
;
}

System.out.println("main end!!");
}
}
class ThreadSub1 extends Thread
{
private Cnt cnt;

public ThreadSub1(Cnt cnt)
{
this.cnt = cnt ;
}

public void run()
{
try
{
for(int i = 0 ; i < 5 ; i++)
{
synchronized(cnt)
{
cnt.cntUp();
System.out.println("Sub1 : " + i + ":" + cnt.getCnt() );
cnt.cntDown();
System.out.println("Sub1 : " + i + ":" + cnt.getCnt() );
}
Thread.sleep(250);
}
}
catch(InterruptedException e)
{
;
}
finally
{
System.out.println("sub1 end!!");
}
}
}
class ThreadSub2 extends Thread
{
private Cnt cnt;

public ThreadSub2(Cnt cnt)
{
this.cnt = cnt ;
}
public void run()
{
try
{
for(int i = 0 ; i < 5 ; i++)
{
synchronized(cnt)
{
cnt.cntUp();
System.out.println("Sub2 : " + i + ":" + cnt.getCnt() );
cnt.cntDown();
System.out.println("Sub2 : " + i + ":" + cnt.getCnt() );
}
Thread.sleep(250);
}
}
catch(InterruptedException e)
{
;
}
finally
{
System.out.println("sub2 end!!");
}
}
}
class Cnt
{
private int cnt = 0;
public void cntUp()
{
cnt++;
}

public void cntDown()
{
cnt--;
}

public int getCnt()
{
return cnt ;
}
}

/*
* 複数スレッドによる共有資源の参照
* =>共有資源利用時にタイミングにより
* 値がおかしくなる
* イメージ
* 代入したタイミング
* 参照したタイミング
* で結果が異なる
* 代入し、結果を参照表示
* Thread1 Thread2
* 代入10
* 参照10
* 代入20
* 参照20
* でも、タイミングによっては
* 代入10
* 代入20
* 参照20
* 参照
* ThreadSamp05に追加
*
* 他のスレッドによる割り込みを禁止
* ->排他制御
* 方法? for文内の処理(1回分) 中、排他指定
* Synchronized (対象変数)
*
* synchronized(cnt)
* {
* cnt.cntUp();
* System.out.println("Sub2 : " + i + ":" + cnt.getCnt() );
* cnt.cntDown();
* System.out.println("Sub2 : " + i + ":" + cnt.getCnt() );
* }
*
*/
public class ThreadSamp06
{
public static void main(String[] args)
{
Cnt cnt = new Cnt();
ThreadSub1 tSub1 = new ThreadSub1(cnt);
ThreadSub2 tSub2 = new ThreadSub2(cnt);
tSub1.setPriority(Thread.MAX_PRIORITY);
tSub2.setPriority(Thread.MIN_PRIORITY);
tSub1.start();
tSub2.start();
try
{
tSub1.join();
tSub2.join();
}
catch(InterruptedException e)
{
;
}

System.out.println("main end!!");
}
}
class ThreadSub1 extends Thread
{
private Cnt cnt;

public ThreadSub1(Cnt cnt)
{
this.cnt = cnt ;
}

public void run()
{
try
{
for(int i = 0 ; i < 5 ; i++)
{
//synchronized(cnt)
//{
cnt.cntUp();
System.out.println("Sub1 : " + i + ":" + cnt.getCnt() );
cnt.cntDown();
System.out.println("Sub1 : " + i + ":" + cnt.getCnt() );
//}
Thread.sleep(250);
}
}
catch(InterruptedException e)
{
;
}
finally
{
System.out.println("sub1 end!!");
}
}
}
class ThreadSub2 extends Thread
{
private Cnt cnt;

public ThreadSub2(Cnt cnt)
{
this.cnt = cnt ;
}
public void run()
{
try
{
for(int i = 0 ; i < 5 ; i++)
{
//synchronized(cnt)
//{
cnt.cntUp();
System.out.println("Sub2 : " + i + ":" + cnt.getCnt() );
cnt.cntDown();
System.out.println("Sub2 : " + i + ":" + cnt.getCnt() );
//}
Thread.sleep(250);
}
}
catch(InterruptedException e)
{
;
}
finally
{
System.out.println("sub2 end!!");
}
}
}
class Cnt
{
private int cnt = 0;

public synchronized void cntUp()
{
if(cnt != 0)
{
try
{
System.out.println("wait");
wait();
}
catch(InterruptedException e )
{
;
}
}
cnt++;
notify();
}

public synchronized void cntDown()
{
if(cnt == 0)
{
try
{
System.out.println("wait");
wait();
}
catch(InterruptedException e )
{
;
}
}
cnt--;
notify();
}

public int getCnt()
{
return cnt ;
}
}

/*
* 方法2 Cntクラスのメソッドに対して指定
* cntUpはcntが0の時だけ
* => 0以外はほかのメソッドが利用中
* =>利用が終わるまで待つ
* cntDownはcntが1の時だけ
* => 1以外はほかのメソッドが利用中
* =>利用が終わるまで待つ
* 改良
* ThreadSub1とThreadSub2の
* for文内の
* synchronized(cnt){ ←コメント
* Cntクラス
* cntUpメソッド
* =>0以外はほかのメソッドが利用中
* =>利用が終わるまで待つ
* cntUpメソッドが排他制御をおこなうメソッドであることを指定
* public synchronized void cntUp()
* {
* if(cnt != 0)
* {
* try
* {
* System.out.println("wait");
* wait();
* }
* catch(InterruptedException e )
* {
* ;
* }
* }
* cnt++;
* }
*
* wait中のメソッド処理を再スタートさせる指定
* notify(); ->スレッドに関係なく再開
* wait中のスレッドがあれば再開
*/


import javax.swing.*;
import java.awt.*;

public class DrawSamp1 extends JFrame
{
public DrawSamp1(String title)
{
super(title);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Dimension scrSize = Toolkit.getDefaultToolkit().getScreenSize();
int w = scrSize.width;
int h = scrSize.height;
setBounds(w/4 , h/4 , w/2 , h/2);
//MyPaintの生成
MyPaint canvas = new MyPaint();
//描画領域への登録
getContentPane().add(canvas);
setVisible(true);
}

public static void main (String[] args)
{
new DrawSamp1("Draw!");
}
}
class MyPaint extends Canvas
{
public MyPaint()
{
super();
}
public void paint(Graphics g)
{
g.drawLine(100,10,100,100);
g.drawLine(10,10,10,100);
g.drawLine(10,10,100,10);
g.drawLine(10,100,100,100);

g.drawRect(100,100,200,200);
g.drawOval(100,100,200,200);
}
}

/*
* WindowsやWebページの描画
* イベント発生時には画面の再描画が発生
* テキストへ入力 文字の絵を描画
* ボタンをクリック
* クリックイメージの絵を描画
* =>描画処理を確認
* =>JFrameを継承したFrame表示
*
* Frameに描画を行うためには、中間コンテナを用意
* Canvasクラスを継承した独自クラスを定義
* =>MyPaintクラス
*
* Canvasクラス 描画をサポートしたクラス
* 利用方法
* Frameの描画を領域に登録
* 実際の描画処理は、MyPaint内で記述
* =>Canvasクラスでは描画が必要な時
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Paintメソッドが呼ばれている
* ~~~~~~~~~~~~~
* =>Paintメソッドをオーバライドし、
* 描画処理を記述
* =>描画が実行される
*
* public void paint(Graphics g)
* {
* g.drawLine(10,10,100,100);
* }
* paintメソッド引数 Graphics g は
* 実行画面の描画領域を指している
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* =>引数gに対して描画を行うことで実効
* g.drawLine(10,10,100,100);
* g. 描画領域
* drawLine 線を描画
* drawLine(開始座標x , 開始座標y , 終端座標x , 終端座標y);
*
* Graphicsクラスには、いくつかの描画メソッドが用意されている
* drawLine 線
* drawRect 四角
* drawOval 円
* drawString テキスト
*
* fillRect 四角・塗りつぶし
* fillOval 円・塗りつぶし
*
* drawRectを利用して 正方形を描画
* 左上座標(100 ,100);
* 幅・高さ(200 ,200);
* Javaの四角形描画メソッドdrawRectの引数
* drawRect(左上横 , 左上縦 , 幅 , 高さ);
* g.drawRect(100,100,200,200);
* 注意 言語によっては 左上と右下座標
*
* drawOvalは指定された引数の四角形の内接円
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class DrawSamp2 extends JFrame
{
public DrawSamp2(String title)
{
super(title);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Dimension scrSize = Toolkit.getDefaultToolkit().getScreenSize();
int w = scrSize.width;
int h = scrSize.height;
setBounds(w/4 , h/4 , w/2 , h/2);
//MyPaintの生成
MyPaint canvas = new MyPaint();
//描画領域への登録
getContentPane().add(canvas);
setVisible(true);
}

public static void main (String[] args)
{
new DrawSamp1("Draw!");
}
}
class MyPaint extends Canvas implements MouseListener
{
int x,y;
public MyPaint()
{
super();
addMouseListener(this);
}
/*public void paint(Graphics g)
{
g.drawLine(10,10,x,y);
}*/
public void update(Graphics g)
{
g.drawLine(10,10,x,y);
}
public void mouseClicked(MouseEvent e)
{
x = e.getX();
y = e.getY();
repaint();
}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mousePressed(MouseEvent e){}
public void mouseReleased(MouseEvent e){}


}

/*
* マウスイベント追加
* マウスのクリックで座標指定
* マウス用のアクションをMyPaintに追加
* =>MyPaintはCanvasを継承済み
* =>マウス用アクションは
* インタフェースを利用
* =>MouseListenerインタフェース
* クリック時、起点(10,10)からクリック座標まで線を描画
* クリック座標の取得
* クリック時メソッド引数より取得できる
* =>mouseClickedメソッドの引数MouseEvent e
* MouseEventクラスのメソッドを利用
* e.getX(); 横座標
* e.getY(); 縦座標
* 再描画 => paintメソッド実行
* repaint();=> paintメソッド実行
*
* を利用すればいい
* ただし、クリック座標取得は=>mouseClickedメソッド
* 描画は =>paintメソッド
* 場所が異なる
* クリック座標を メンバ変数に代入
* paintメソッド実行
* paintメソッド内 メンバ変数を利用して描画
*
* インタフェースを利用する方法は
* implements 利用するインタフェース
* インタフェースで定義されているすべての
* メソッドをオーバライド
* MouseListenerの監視を追加、コンストラクタに
*
* * paintメソッドは
* クリアと描画を実行
* クリックごとに新しく線を引いていた
* updateメソッドは 描画のみ行う(クリアなし)
* クリア=> 背景色で描画領域を描画
*
* Canvasは awtを利用
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class DrawSamp3 extends JFrame
{
public DrawSamp3(String title)
{
super(title);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Dimension scrSize = Toolkit.getDefaultToolkit().getScreenSize();
int w = scrSize.width;
int h = scrSize.height;
setBounds(w/4 , h/4 , w/2 , h/2);
//MyPaintの生成
MyPaint canvas = new MyPaint();
//描画領域への登録
getContentPane().add(canvas);
setVisible(true);
}

public static void main (String[] args)
{
new DrawSamp3("Draw!");
}
}
class MyPaint extends JPanel implements MouseListener
{
int x1,y1, x2,y2;//2つの座標
boolean drawMode = false ; //repaint(); 実行の有無
public MyPaint()
{
super();
addMouseListener(this);
}

public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawLine(x1,y1,x2,y2);
}

public void mouseClicked(MouseEvent e)
{
if(drawMode)
{
x2 = e.getX();
y2 = e.getY();
drawMode = false;
repaint();
}
else
{
x1 = e.getX();
y1 = e.getY();
drawMode = true;
}
}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mousePressed(MouseEvent e){}
public void mouseReleased(MouseEvent e){}


}

/*
* MyPaintを Canvas継承から JPanel継承に変更
* MouseListenerはそのまま
* 描画は
* public void paintComponent(Graphics g)
* 変更して実行 updateメソッドは削除
* public void paintComponent(Graphics g)
* {
* g.drawLine(10,10,x,y);
* }
* クリアは必要な時に
* super.paintComponent(g);
* を実行
* 改良
* public void paintComponent(Graphics g)
* {
* super.paintComponent(g);
* g.drawLine(10,10,x,y);
* }
* 改良 2点間をクリック
* 1回目のクリック座標と
* 2回目のクリック座標を描画
* 考え方
* クリックイベント用メソッドは同じ位置
* 1回目 座標を記録
* 2回目 座標を記録し描画
* 1回目か2回目かの判定(描画の有無の判定)
* が必要
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class DrawSamp3 extends JFrame
{
public DrawSamp3(String title)
{
super(title);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Dimension scrSize = Toolkit.getDefaultToolkit().getScreenSize();
int w = scrSize.width;
int h = scrSize.height;
setBounds(w/4 , h/4 , w/2 , h/2);
//MyPaintの生成
MyPaint canvas = new MyPaint();
//描画領域への登録
getContentPane().add(canvas);
setVisible(true);
}

public static void main (String[] args)
{
new DrawSamp3("Draw!");
}
}
class MyPaint extends JPanel implements MouseListener , MouseMotionListener
{
int x1,y1, x2,y2;//2つの座標
boolean drawMode = false ; //repaint(); 実行の有無
public MyPaint()
{
super();
addMouseListener(this);
addMouseMotionListener(this);
}

public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.drawLine(x1,y1,x2,y2);
}

public void mouseClicked(MouseEvent e)
{/*
if(drawMode)
{
x2 = e.getX();
y2 = e.getY();
drawMode = false;
repaint();
}
else
{
x1 = e.getX();
y1 = e.getY();
drawMode = true;
}*/
}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mousePressed(MouseEvent e)
{
x1 = e.getX();
y1 = e.getY();
}
public void mouseReleased(MouseEvent e)
{
x2 = e.getX();
y2 = e.getY();
repaint();
}

public void mouseDragged(MouseEvent e)
{
x2 = e.getX();
y2 = e.getY();
repaint();
}
public void mouseMoved(MouseEvent e){}
/*
* マウスドラッグ時描画
* マウスを押した座標 1つ目の座標
* ドラッグ中座標 2つ目の座標として再描画
* MouseMotionListenerを利用(追加)
* マウスを離したとき座標 2つ目の座標として再描画
* mouseReleased
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class DrawSamp5 extends JFrame
{
public DrawSamp5(String title)
{
super(title);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Dimension scrSize = Toolkit.getDefaultToolkit().getScreenSize();
int w = scrSize.width;
int h = scrSize.height;
setBounds(w/4 , h/4 , w/2 , h/2);
MyPaint canvas = new MyPaint();
getContentPane().add(canvas);
setVisible(true);
}

public static void main (String[] args)
{
new DrawSamp5("Draw!");
}
}
class MyPaint extends JPanel implements MouseListener , MouseMotionListener
{
int x1,y1, x2,y2;
int x, y , w , h;
boolean drawMode = false ;
public MyPaint()
{
super();
addMouseListener(this);
addMouseMotionListener(this);
}

public void paintComponent(Graphics g)
{
super.paintComponent(g);

g.drawRect(getDrawX(), getDrawY() , getDrawW() , getDrawH());
//g.drawLine( x1 , y1 , x2 , y2 );
}

public void mouseClicked(MouseEvent e)
{

}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mousePressed(MouseEvent e)
{
x1 = e.getX();
y1 = e.getY();
}
public void mouseReleased(MouseEvent e)
{
x2 = e.getX();
y2 = e.getY();
repaint();
}

public void mouseDragged(MouseEvent e)
{
x2 = e.getX();
y2 = e.getY();
repaint();
}
public void mouseMoved(MouseEvent e){}

public int getDrawX() //←内部のみで扱うメソッドならばprivate宣言もあり
{
if( x1 < x2)
{
x = x1;
}
else
{
x = x2;
}
return x;
}
public int getDrawY()
{
if(y1 < y2)
{
y = y1;
}
else
{
y = y2;
}
return y;
}
public int getDrawW()
{
if( x1 < x2)
{
w = x2 - x1;
}
else
{
w = x1 - x2;
}
return w;
}
public int getDrawH()
{
if(y1 < y2)
{
h = y2 - y1;
}
else
{
h = y1 - y2;
}
return h;
}
}

/*
* DrawLine( 開始x, 開始y, 終端x, 終端y)
* でも、四角描画のDrawRectは
* DrawRect( 左上x, 左上y, 幅 , 高さ )
* 考え方 2点間の座標(x1,x2)(y1,y2)より,
* 位置関係を元に
* 左上x, 左上y, 幅 , 高さ を計算後表示
* int x,y,w,h;
* super.paintConponent(g);
* x,y,w,hの値を設定
* 例
* if( x1 > y1)
* {
* x = x1;
* w = x2 - x1;
* }
* else
* {
* x = x2;
* w = x1 - x2;
* }
* if(y1 > y2)
* {
* y = y1;
* h = y1 - y2;
* }
* else
* {
* y = y2;
* h = y2 - y1;
* }
*
*
* g.drawRect(x,y,w,h);
*
* 改良
* 描画時座標、幅、高さを調べるメソッドを定義
* getDrawX() 左上x
* getDrawY() 左上y
* getDrawW() 幅
* getDrawH() 高さ
* 利用イメージ
* g.drawRect(getDrawX(),getDrawY(),getDrawW(),getDrawH());
*
* 内部的に使うだけであれば
* public ではなく private宣言もあり
*
* 別の記述 3項演算子も利用できる
* private int getDrawX()
* {
* return x1 < x2?x1:x2 ;
* }
*
* private int getDrawW()
* {
* return x1 < x2?x2 - x1:x1 - x2;
* }
* 条件 ? 処理1(真) : 処理2(偽) ;
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class DrawSamp6 extends JFrame
{
public DrawSamp6(String title)
{
super(title);
setDefaultCloseOperation(EXIT_ON_CLOSE);
Dimension scrSize = Toolkit.getDefaultToolkit().getScreenSize();
int w = scrSize.width;
int h = scrSize.height;
setBounds(w/4 , h/4 , w/2 , h/2);
MyPaint canvas = new MyPaint();
getContentPane().add(canvas);
setVisible(true);
}

public static void main (String[] args)
{
new DrawSamp6("Draw!");
}
}
class MyPaint extends JPanel implements MouseListener , MouseMotionListener
{
int x1,y1, x2,y2;
int x, y , w , h;
int wx , wy;
boolean drawMode = false ;
public MyPaint()
{
super();
addMouseListener(this);
addMouseMotionListener(this);
}

public void paintComponent(Graphics g)
{
//super.paintComponent(g);
//g.drawRect(getDrawX(), getDrawY() , getDrawW() , getDrawH());
//g.setColor(Color.white);
if( wx != -1)
{
g.setXORMode(Color.white);
//g.drawLine( x1 , y1 , wx , wy);
g.drawRect(getDrawWX(), getDrawWY() , getDrawWW() , getDrawWH());
}
g.setColor(Color.black);
//g.drawLine( x1 , y1 , x2 , y2 );
g.drawRect(getDrawX(), getDrawY() , getDrawW() , getDrawH());
wx = x2;
wy = y2;
}

public void mouseClicked(MouseEvent e)
{

}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mousePressed(MouseEvent e)
{
wx = -1;
x1 = e.getX();
y1 = e.getY();
}
public void mouseReleased(MouseEvent e)
{
x2 = e.getX();
y2 = e.getY();
repaint();
}

public void mouseDragged(MouseEvent e)
{
x2 = e.getX();
y2 = e.getY();
repaint();
}
public void mouseMoved(MouseEvent e){}

public int getDrawX()
{
if( x1 < x2)
{
x = x1;
}
else
{
x = x2;
}
return x;
}
public int getDrawY()
{
if(y1 < y2)
{
y = y1;
}
else
{
y = y2;
}
return y;
}
public int getDrawW()
{
if( x1 < x2)
{
w = x2 - x1;
}
else
{
w = x1 - x2;
}
return w;
}
public int getDrawH()
{
if(y1 < y2)
{
h = y2 - y1;
}
else
{
h = y1 - y2;
}
return h;
}

private int getDrawWX()
{
return x1 < wx?x1:wx;
}
private int getDrawWY()
{
return y1 < wy?y1:wy;
}
private int getDrawWW()
{
return x1 < wx?wx - x1:x1 - wx;
}
private int getDrawWH()
{
return y1 < wy?wy - y1:y1 - wy;
}
}
↑補足
/*
* super.paintComponent(g); ←クリア
* クリア → 背景色による塗りつぶし
* 別の方法によりクリア
* super.paintComponent(g);
* g.drawLine( x1 , y1 , x2 , y2 );
* の繰り返し
* でも、クリアの目的は
* ドラッグ中 → 直前の線をクリアできればよい
* → 直前の線を 背景色で塗りつぶす
* setColorを利用
* 例
* 背景色 Color.white
* 描画職 Color.black
* 処理イメージ
* g.setColor(Color.white);
* g.drawLine( x1 , y1 , 直前のx , 直前のy);
* g.setColor(Color.black);
* g.drawLine( x1 , y1 , x2 , y2 );
* 直前のx , 直前のy → 保持しておく
* 直前のx = x2;
* 直前のy = y2;
* int wx , wy; を用意
* 直前の線を 背景色で塗りなおした
* 別の方法 背景色と違うところのみ描画
* 差分描画
* 色は 三原色を それぞれ 0〜255(8ビット) 表現
* 2つの色の違い → ビットの異なる部分
* ビットの違いを調べる演算子を利用
* 同じなら 0
* 違うなら 1
* を求めて(XOR)描画
* Glaphicsクラスのメソッド setXORModeを利用
* //g.setColor(Color.white);
* g.setXORMode(Color.white);
* 描画色とColor.white の違いを設定
* g.drawLine( x1 , y1 , wx , wy);
*
* g.setXORMode(Color.white);
* g.drawLine( x1 , y1 , wx , wy);
* は、repaint()で必ず実行される
* =>再描画時に必ず実行される
* マウスプレス時 x1 , y1
* ドラッグ時 x2 , y2
* 最初の
* g.drawLine( x1 , y1 , wx , wy);
* マウスプレス時 x1 , y1
* wx , wyは? 初期値0
* 元の描画がない 標準は Color.black
* → 結果 逆転表示(Color.black)
* Color.white 0,0,0
* Color.black 255,255,255
*
* 解決
* wxに正しい値(直前に線を引いてあるとき)の時
* XOR描画
*
* マウスプレス時 wx = -1 ;
* paintComponentでは
* if(wx != -1)
* {
* g.setXORMode(Color.white);
* g.drawLine( x1 , y1 , wx , wy);
* }
* g.drawLine(x1 , y1 , x2 , y2);
* wx = x2;←1っ買目のドラッグ後設定される
* wy = y2;
* 注意 g.setColor(Color.white);は
* 同じ座標に対する描画は
* 反転 → 反転 → 反転
* のようになっている
*
* 改良
* 四角描画に変更
* 反転描画用座標,幅,高さ取得メソッドを定義
* getDrawWX() 左上x
* getDrawWY() 左上y
* getDrawWW() 幅
* getDrawWH() 高さ
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class DrawSamp7 extends JFrame
{
public DrawSamp7(String title)
{
super(title);

setDefaultCloseOperation(EXIT_ON_CLOSE);
Dimension scrSize = Toolkit.getDefaultToolkit().getScreenSize();
int w = scrSize.width;
int h = scrSize.height;
setBounds(w/4 , h/4 , w/2 , h/2);
MyPaint canvas = new MyPaint();
canvas.setDrawType(MyPaint.DRAW_OVAL);
canvas.setDrawColor();
getContentPane().add(canvas);
setVisible(true);
}

public static void main (String[] args)
{
new DrawSamp7("Draw!");
}
}
class MyPaint extends JPanel implements MouseListener , MouseMotionListener
{
int x1,y1, x2,y2;
int x, y , w , h;
int wx , wy;
int drawType;
boolean drawMode = false ;
boolean setMode = false ;
Color color;
public final static int DRAW_LINE = 0;
public final static int DRAW_RECT = 1;
public final static int DRAW_OVAL = 2;
Image backImage = null; //2つ目の描画領域用変数

public MyPaint()
{
super();
addMouseListener(this);
addMouseMotionListener(this);
}

public void setDrawType(int drawType)
{
this.drawType = drawType;
}

public void setDrawColor()
{
try
{
color = JColorChooser.showDialog(null , "Color" , Color.black);

}
catch(HeadlessException e)
{
;
}
}

public void paintComponent( Graphics g)
{
Graphics bg;
if( backImage == null ) //初回かどうか
{
backImage = createImage(getSize().width , getSize().height); //生成
bg = backImage.getGraphics();//←Graphics取得
super.paintComponent(bg); //←クリア bgを対象に
}
else//2回目以降
{
bg = backImage.getGraphics();//取得のみ
}

if( setMode == true )
{
bg.setColor(color);

switch (drawType)
{
case DRAW_LINE:
bg.drawLine( x1 , y1 , x2 , y2 );
break;

case DRAW_RECT:
bg.drawRect(getDrawX(), getDrawY() , getDrawW() , getDrawH());
break;

case DRAW_OVAL:
bg.drawOval(getDrawX(), getDrawY() , getDrawW() , getDrawH());
break;
}
g.drawImage( backImage , 0 , 0 , this );
}
else
{
g.setColor(color);
g.drawImage( backImage , 0 , 0 , this );

if( drawType == DRAW_LINE )
{
g.drawLine( x1 , y1 , x2 , y2 );
}
if( drawType == DRAW_RECT )
{
g.drawRect(getDrawX(), getDrawY() , getDrawW() , getDrawH());
}
if( drawType == DRAW_OVAL )
{
g.drawOval(getDrawX(), getDrawY() , getDrawW() , getDrawH());
}
}
}

public void mouseClicked(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
public void mouseExited(MouseEvent e){}
public void mousePressed(MouseEvent e)
{
wx = -1;
x1 = e.getX();
y1 = e.getY();
}
public void mouseReleased(MouseEvent e)
{
x2 = e.getX();
y2 = e.getY();
setMode = true;
repaint();
}

public void mouseDragged(MouseEvent e)
{
x2 = e.getX();
y2 = e.getY();
setMode = false;
repaint();
}
public void mouseMoved(MouseEvent e){}

public int getDrawX()
{
if( x1 < x2)
{
x = x1;
}
else
{
x = x2;
}
return x;
}
public int getDrawY()
{
if(y1 < y2)
{
y = y1;
}
else
{
y = y2;
}
return y;
}
public int getDrawW()
{
if( x1 < x2)
{
w = x2 - x1;
}
else
{
w = x1 - x2;
}
return w;
}
public int getDrawH()
{
if(y1 < y2)
{
h = y2 - y1;
}
else
{
h = y1 - y2;
}
return h;
}

private int getDrawWX()
{
return x1 < wx?x1:wx;
}
private int getDrawWY()
{
return y1 < wy?y1:wy;
}
private int getDrawWW()
{
return x1 < wx?wx - x1:x1 - wx;
}
private int getDrawWH()
{
return y1 < wy?wy - y1:y1 - wy;
}
}
/*
* class MyPaint extends JPanelの結果
* this. が1つ目の描画領域を持つ
* ->2つ目の描画領域はMyPaintn内で生成
* =>MyPaint にメンバ変数宣言
* Image backImage = null;
* =>paintComponentメソッドの描画処理で
* 標準の描画領域は メソッド引数 g
* 2つ目の描画領域用にローカル変数定義
* Graphics bg;
* paintComponentメソッドの描画処理
* 初回のみ 2つ目の描画領域生成とクリア
* 毎回 2つ目の描画領域よりGraphics取得
* gおよびbgを利用した描画
* if( backImage == null );
* {
* backImage = createImage(getSize().width , getSize().height);
* bg = backImage.getGraphics();
* super.paintComponent(bg);
* }
* else
* {
* bg = backImage.getGraphics();
* }
* gおよびbgを利用した描画 とりあえず DrawLineで
* マウスのドラッグ中と離したときで異なる
* 離したとき確定→2つ目の描画領域に描画(描画保存)
* => boolean setMode = false; を用意
* カラーダイアログ JColorChooser を利用して描画色設定
* MyPaint に setDrawColor メソッド用意
* 利用方法 DrawSamp7のコンストラクタで
* MyPaint canvas = new MyPaint();←生成後
* canvas.setDrawColor();
* getContentPane().add( canvas );
* JColorChooserのヘルプより ダイアログ表示メソッド
* public static Color showDialog(Component component,String title , Color initialColor)
* ↑表示位置 ↑ダイアログタイトル ↑カラー
* → static メソッドは、クラス名.で利用できる
* =>
* public void setDrawColor()
* {
* Color color = JColorChooser.showDialog( null , "描画色" , Color.black );
* if(color != null)
* {
* drawColor = color;
* }
* }
* ※drawColorは、MyPaintのメンバ変数として宣言 Color drawColor;
* 描画時利用
* bg.setColor( drawColor );
* g.setColor( drawColor );
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class DrawEnsyu1111 extends JFrame implements WindowStateListener , ComponentListener
{
MyPaint canvas = new MyPaint();

public DrawEnsyu1111(String title)
{
super(title);

setDefaultCloseOperation(EXIT_ON_CLOSE);
Dimension scrSize = Toolkit.getDefaultToolkit().getScreenSize();
int w = scrSize.width;
int h = scrSize.height;
setBounds(w/4 , h/4 , w/2 , h/2);

JMenu mFile = new JMenu( "ファイル" );
mFile.add(new JMenuItem( new mFCloseAction() ) );

JMenu mDrawType = new JMenu( "描画タイプ" );
mDrawType.add(new JMenuItem( new mDrawLineAction() ) );
mDrawType.add(new JMenuItem( new mDrawRectAction() ) );
mDrawType.add(new JMenuItem( new mDrawOvalAction() ) );

JMenu mEdit = new JMenu( "編集" );
mEdit.add(new JMenuItem( new mEditColorAction() ) );

JMenuBar menu = new JMenuBar();
menu.add( mFile );
menu.add( mDrawType );
menu.add( mEdit );

setJMenuBar( menu );

getContentPane().add(canvas);
setVisible(true);
addWindowStateListener(this);
addComponentListener(this);
}
=======================中略================================
public void windowStateChanged(WindowEvent e)
{
canvas.sizeMode = true ;
}

public void componentHidden(ComponentEvent e){}
public void componentMoved(ComponentEvent e){}
public void componentResized(ComponentEvent e)
{
canvas.sizeMode = true;
}
public void componentShown(ComponentEvent e){}


}
class MyPaint extends JPanel implements MouseListener , MouseMotionListener
{
int x1,y1, x2,y2;
int x, y , w , h;
int wx , wy;
boolean drawMode = false ;
boolean setMode = false ;
boolean sizeMode = false;
Color color = Color.black;
public final static int DRAW_LINE = 0;
public final static int DRAW_RECT = 1;
public final static int DRAW_OVAL = 2;
private int drawType = DRAW_LINE;
Image backImage = null;

public MyPaint()
{
super();
addMouseListener(this);
addMouseMotionListener(this);
}

public void setDrawType(int drawType)
{
this.drawType = drawType;
}

public void setDrawColor()
{
try
{
color = JColorChooser.showDialog(null , "Color" , color);
if(color == null)
{
color = Color.black;
}
}
catch(HeadlessException e)
{
;
}
}

public void paintComponent( Graphics g)
{
Graphics bg;
if( backImage == null )
{
backImage = createImage(getSize().width , getSize().height);
bg = backImage.getGraphics();
super.paintComponent(bg);
}
else
{
if( sizeMode )
{
Image image = createImage(getSize().width , getSize().height);
image.getGraphics().drawImage( backImage , 0 , 0 , this );
backImage = image;
bg = backImage.getGraphics();

sizeMode = false;
}
else
{
bg = backImage.getGraphics();
}
}
==========================以下略==============================
以下DrawSamp7参照してね

ログインすると、残り2件のコメントが見れるよ

mixiユーザー
ログインしてコメントしよう!

ひろ☆みんを崇める会! 更新情報

ひろ☆みんを崇める会!のメンバーはこんなコミュニティにも参加しています

星印の数は、共通して参加しているメンバーが多いほど増えます。