#author("2019-12-05T17:27:14+09:00","ocha","ocha")
#author("2020-01-09T16:07:39+09:00","ocha","ocha")
[[Lecture]]

*Java プログラミング入門 [#kd7c750b]


このページは、学部2年生向け授業である、「マルチメディアプログラミング実習」
のために用意しました。

(Wikiの仕様で大文字小文字が混在した英単語に疑問符?が追加されるところがありますが、無視してください。)


**第13章 様々なコンポーネントとレイアウト [#qb662dcc]

***複雑なボタンの配置例 [#g43d30cb]

ボタンを多数配置した例です。

#ref(complicated.png)
#ref(LectureMMP07/complicated.png)

下がプログラムです。動かしてみましょう。長いのでコピペして良いです。動作を確認してください。またレイアウト方法を確認してください。

 import java.awt.*;
 import javax.swing.*;
 import java.awt.event.*;
 
 public class ComplicatedLayoutSample extends JFrame implements ActionListener {
 	
 	public void initialize() {
 		JPanel panel1 = new JPanel();
 		JPanel panel2= new JPanel();
 		JPanel panel3= new JPanel();
 		JPanel panel4= new JPanel();
 		JPanel panel5= new JPanel();
 		
 		panel1.setLayout(new FlowLayout());
 		for (int i=1; i<=3; i++) {
 			JButton btn = new JButton("NORTH" + i);
 			btn.addActionListener(this);
 			panel1.add(btn);
 		}
 		panel2.setLayout(new BoxLayout(panel2, BoxLayout.Y_AXIS));
 		for (int i=1; i<=3; i++) {
 			JButton btn = new JButton("WEST" + i);
 			btn.addActionListener(this);
 			panel2.add(btn);
 		}		
 		panel3.setLayout(new GridLayout(3,2));
 		for (int i=1; i<=6; i++) {
 			JButton btn = new JButton("CENTER" + i);
 			btn.addActionListener(this);
 			panel3.add(btn);
 		}	
 		panel4.setLayout(new BorderLayout());
 		JButton btn1 = new JButton("EAST1");
 		btn1.addActionListener(this);
 		panel4.add(btn1, BorderLayout.NORTH);
 		JButton btn2 = new JButton("EAST2");
 		btn2.addActionListener(this);
 		panel4.add(btn2, BorderLayout.SOUTH);
 
 		panel5.setLayout(new BoxLayout(panel5, BoxLayout.X_AXIS));
 		for (int i=1; i<=4; i++) {		
 			JButton btn = new JButton("SOUTN" + i);
 			btn.addActionListener(this);
 			panel5.add(btn);
 			}	
 		
 				
 		Container container = this.getContentPane();
 		container.add(panel1,BorderLayout.NORTH);
 		container.add(panel2,BorderLayout.WEST);
 		container.add(panel3,BorderLayout.CENTER);
 		container.add(panel4,BorderLayout.EAST);
 		container.add(panel5,BorderLayout.SOUTH);
 
 		this.setSize(400,200);
 		this.setVisible(true);
 	}
 	
 	public void actionPerformed(ActionEvent e) {
 		System.out.println( ((JButton)e.getSource()).getText()   );
 	}
 	
 	public static void main(String[] args) {
 		ComplicatedLayoutSample cls = new ComplicatedLayoutSample();
 		cls.initialize();	
 	}
 }
 

コピペしてしまいましたが、動作はしっかり確認しましょう。


 import java.awt.*;
 import javax.swing.*;
 import java.awt.event.*;
 
 public class ComplicatedLayoutSample extends JFrame implements ActionListener {

Action ListenerをインプレメントしたJFrameサブクラスです。
 	
 	public void initialize() {
 		JPanel panel1 = new JPanel();
 		JPanel panel2= new JPanel();
 		JPanel panel3= new JPanel();
 		JPanel panel4= new JPanel();
 		JPanel panel5= new JPanel();
 		
5個のパネルを用意しています。動作例を見るとわかりますが、上下左右と中央の五枚のパネルを貼り付けています。

 		panel1.setLayout(new FlowLayout());
 		for (int i=1; i<=3; i++) {
 			JButton btn = new JButton("NORTH" + i);
 			btn.addActionListener(this);
 			panel1.add(btn);
 		}

最初のパネルは、「北側」に貼り付けるパネルです。(ウィンドウの上部)。
ここにNORTH + 番号の名前のボタンを3個作り、アクションリスナーに自分自身を登録して、北側パネルに貼り付けています。以下同様です。フローレイアウトを使っています。貼り付ける相手の形に合わせて柔軟に配置されます。

 		panel2.setLayout(new BoxLayout(panel2, BoxLayout.Y_AXIS));
 		for (int i=1; i<=3; i++) {
 			JButton btn = new JButton("WEST" + i);
 			btn.addActionListener(this);
 			panel2.add(btn);
 		}		
  
		panel3.setLayout(new GridLayout(3,2));
 		for (int i=1; i<=6; i++) {
 			JButton btn = new JButton("CENTER" + i);
 			btn.addActionListener(this);
 			panel3.add(btn);
 		}	
  
		panel4.setLayout(new BorderLayout());
 		JButton btn1 = new JButton("EAST1");
 		btn1.addActionListener(this);
 		panel4.add(btn1, BorderLayout.NORTH);
 		JButton btn2 = new JButton("EAST2");
 		btn2.addActionListener(this);
 		panel4.add(btn2, BorderLayout.SOUTH);
 
 		panel5.setLayout(new BoxLayout(panel5, BoxLayout.X_AXIS));
 		for (int i=1; i<=4; i++) {		
 			JButton btn = new JButton("SOUTN" + i);
 			btn.addActionListener(this);
 			panel5.add(btn);
 			}	
 
西側パネル、中央パネル、東側パネル、南側パネルにボタンを貼り付けています。すべてのアクションリスナーに自分自身を登録しています。ボタン配置のレイアウトは、Y軸方向のボックスレイアウト、3 x 2の格子レイアウト、ボーダーレイアウト、そしてX軸方向のボックスレイアウトです。ウィンドウをリサイズして、レイアウトの特徴を確認してください。
 				
 		Container container = this.getContentPane();
 		container.add(panel1,BorderLayout.NORTH);
 		container.add(panel2,BorderLayout.WEST);
 		container.add(panel3,BorderLayout.CENTER);
 		container.add(panel4,BorderLayout.EAST);
 		container.add(panel5,BorderLayout.SOUTH);

次に、フレームのコンテナーを取り寄せて、これに五枚のパネルを貼り付けています。レイアウトはボーダーレイアウトで、東西南北、中央に貼り付けています。ボタンだけでなく、コンテナへのパネル貼り付けでもレイアウトが利用できまう。
 
 		this.setSize(400,200);
 		this.setVisible(true);
 	}

あとはサイズを調整しているだけです。
 	
 	public void actionPerformed(ActionEvent e) {
 		System.out.println( ((JButton)e.getSource()).getText()   );
 	}

イベントリスナーのためのメソッドです。ボタンに書かれた名前をget Textで取得して表示しています。
 	
 	public static void main(String[] args) {
 		ComplicatedLayoutSample cls = new ComplicatedLayoutSample();
 		cls.initialize();	
 	}
 }

こちらはいつものメインプログラムです。
 

***テキストフィールドを使う [#x3cf24f2]

次のプログラムは、テキストフィールド2個とボタン1個を表示します。
動作を確認してください。テキストフィールドに文字を入れてみてください。
イベントハンドラーが全く実装されていないので、ボタンを押しても何も起こりません。

#ref(LectureMMP07/textfield1.png)

 import java.awt.*;
 import javax.swing.*;
 import java.awt.event.*;
 
 public class JTextFieldSample extends JFrame {
 JButton button;
 JTextField textleft, textright;
 
 public void initialize() {
         button = new JButton("left to right");
         textleft= new JTextField(10);
         textright= new JTextField(10);
         JPanel panel = new JPanel();
         
         panel.setLayout(new BorderLayout());
         panel.add(textleft, BorderLayout.WEST);
         panel.add(textright, BorderLayout.EAST);
         panel.add(button, BorderLayout.SOUTH);
         
         this.getContentPane().add(panel);
         
         this.setTitle("JTextFieldSample");
         this.pack();
         this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         this.setVisible(true);
 }
 
 public static void main(String[] args){
         JTextFieldSample sample = new JTextFieldSample();
         sample.initialize();
 }
 
 }

演習:このプログラムで、left to rightボタンを押した時に、左のテキストフィールドの内容が右に移動する(左は空になる)ように変更してください。

ヒント:JTextFieldのマニュアルを見て、テキストをゲットしたりセットするメソッドを探してください。

#ref(LectureMMP07/textfield1.png)

https://docs.oracle.com/javase/jp/8/docs/api/index.html

ヒント:

 getText()とsetText("xxx")を使います。

解答例:

 import java.awt.*;
 import javax.swing.*;
 import java.awt.event.*;
 
 public class JTextFieldSample extends JFrame implements ActionListener {
 JButton button;
 JTextField textleft, textright;
 
 public void initialize() {
         button = new JButton("left to right");
         button.addActionListener(this);
         textleft= new JTextField(10);
         textright= new JTextField(10);
         JPanel panel = new JPanel();
         
         panel.setLayout(new BorderLayout());
         panel.add(textleft, BorderLayout.WEST);
         panel.add(textright, BorderLayout.EAST);
         panel.add(button, BorderLayout.SOUTH);
         
         this.getContentPane().add(panel);
         
         this.setTitle("JTextFieldSample");
         this.pack();
         this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         this.setVisible(true);
 }
 
  public void actionPerformed(ActionEvent e) {
         textright.setText(textleft.getText());
         textleft.setText("");
  }
 
 public static void main(String[] args){
         JTextFieldSample sample = new JTextFieldSample();
         sample.initialize();
 }
 
 }


演習:このプログラムに、右のテキストフィールドをクリアするclearボタンを追加してください。 こんなのをつくってください。

https://i.gyazo.com/999f1e766551a994186cc3d159bde0bf.png

ヒント:4個のアイテムをパネルにつけることになります。2 x 2のグリッドレイアウトを使ってみましょう。

          panel.setLayout(new GridLayout(2,2));
 
この後、テキストフィールドとボタンをaddしていけば、左上から順番に割り当ててくれます。

解答例:

 import java.awt.*;
 import javax.swing.*;
 import java.awt.event.*;
 
 public class JTextFieldSample extends JFrame implements ActionListener {
 JButton button, clearButton;
 JTextField textleft, textright;
 
 public void initialize() {
         button = new JButton("left to right");
         button.addActionListener(this);
         clearButton = new JButton("clear");
         clearButton.addActionListener(this);
         textleft= new JTextField(10);
         textright= new JTextField(10);
         JPanel panel = new JPanel();
         
         panel.setLayout(new GridLayout(2,2));
         panel.add(textleft);
         panel.add(textright);
         panel.add(button);
         panel.add(clearButton);
          
         this.getContentPane().add(panel);
         
         this.setTitle("JTextFieldSample");
         this.pack();
         this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         this.setVisible(true);
 }
 
  public void actionPerformed(ActionEvent e) {
        if(e.getSource()==(button)){
                textright.setText(textleft.getText());
                textleft.setText("");
        }else{
                textright.setText("");
        }
  }
 
 public static void main(String[] args){
         JTextFieldSample sample = new JTextFieldSample();
         sample.initialize();
 }
 
 }



***ラジオボタンとチェックボックス [#f84fe7de]

#ref(JRadioButton.png)

ラジオボタンとチェックボックスの例です。ラジオボタンを排他制御するには、ボタングループを使います。

 import java.awt.*;
 import javax.swing.*;
 import java.awt.event.*;
 
 public class JRadioButtonSample extends JFrame {
 
    public void initialize() {
        this.setTitle("Radio Buttons");
 
        JPanel panel1 = new JPanel();
        JPanel panel2 = new JPanel();
 
        JRadioButton radio1 = new JRadioButton("for here");
        JRadioButton radio2 = new JRadioButton("to go");
        ButtonGroup group = new ButtonGroup();
        group.add(radio1);
        group.add(radio2);
    
        panel1.setLayout(new GridLayout(2,1));
        panel2.setLayout(new GridLayout(3,1));
    
        panel1.add(radio1);
        panel1.add(radio2);
    
        panel2.add(new JCheckBox("with Drink"));
        panel2.add(new JCheckBox("with Salad"));
        panel2.add(new JCheckBox("with Cake"));
    
        Container container = this.getContentPane();
        container.add(panel1,BorderLayout.WEST);
        container.add(panel2,BorderLayout.EAST);
        
        this.pack();
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
 
    public static void main (String args[]) {
        JRadioButtonSample jrbs = new JRadioButtonSample();
        jrbs.initialize();
    }
    
 }

***ラジオボタンとラベル [#v8a68d05]

演習:上で作ったプログラムに、JLabelのラベルを一枚追加しましょう。下部に追加します。

#ref(lunch1.png)


ヒント:

ラベルはこんな感じで作ります。センタリングの指定はこのようにします。

        JLabel label = new JLabel("1000 yen");
        label.setHorizontalAlignment(JLabel.CENTER);

ラベルのためにパネルは用意しなくても良いようです。コンテナにaddすれば良いようです。この時、下部に追加するよう指定します。

        container.add(label,BorderLayout.SOUTH);


解答例:

 import java.awt.*;
 import javax.swing.*;
 import java.awt.event.*;
 
 public class JRadioButtonSample2 extends JFrame {
 
	public void initialize() {
        this.setTitle("Radio Buttons");
 
        JPanel panel1 = new JPanel();
        JPanel panel2 = new JPanel();
        
        JLabel label = new JLabel("1000 yen");
        label.setHorizontalAlignment(JLabel.CENTER);
        
        JRadioButton radio1 = new JRadioButton("for here");
        JRadioButton radio2 = new JRadioButton("to go");
        ButtonGroup group = new ButtonGroup();
        group.add(radio1);
        group.add(radio2);
    
        panel1.setLayout(new GridLayout(2,1));
        panel2.setLayout(new GridLayout(3,1));
    
        panel1.add(radio1);
        panel1.add(radio2);
    
        panel2.add(new JCheckBox("with Drink"));
        panel2.add(new JCheckBox("with Salad"));
        panel2.add(new JCheckBox("with Cake"));
    
        Container container = this.getContentPane();
        container.add(panel1,BorderLayout.WEST);
        container.add(panel2,BorderLayout.EAST);
        container.add(label,BorderLayout.SOUTH);
        
        this.pack();
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
 
    public static void main (String args[]) {
        JRadioButtonSample2 jrbs2 = new JRadioButtonSample2();
        jrbs2.initialize();
    }
    
 }

***ラジオボタンとチェックボックスのイベントに対応する [#ybba9da5]

演習:上の例で、ラジオボタンとチェックボックスがクリックされたらhelloと表示するようプログラムしましょう。

ヒント:

- このクラスのインスタンスでイベントを受け取るようにします
- このクラスの定義でAction Listenerをimplementします。
-  actionPerformedメソッドを作ります。その中でSystem.out.printlnでhelloと表示します。
- ラジオボタンとチェックボックスにadd Action Listenerでこのインスタンスを登録します。

解答例:

 import java.awt.*;
 import javax.swing.*;
 import java.awt.event.*;
 
 public class JRadioButtonSample2 extends JFrame implements ActionListener {
 
	public void initialize() {
        this.setTitle("Radio Buttons");
 
        JPanel panel1 = new JPanel();
        JPanel panel2 = new JPanel();
        
        JLabel label = new JLabel("1000 yen");
        label.setHorizontalAlignment(JLabel.CENTER);
        
        JRadioButton radio1 = new JRadioButton("for here");
        JRadioButton radio2 = new JRadioButton("to go");
        ButtonGroup group = new ButtonGroup();
        group.add(radio1);
        group.add(radio2);
    
        panel1.setLayout(new GridLayout(2,1));
        panel2.setLayout(new GridLayout(3,1));
    
        panel1.add(radio1);
        panel1.add(radio2);
        radio1.addActionListener(this);
        radio2.addActionListener(this);
    
        JCheckBox check1 = new JCheckBox("with Drink");
        JCheckBox check2 = new JCheckBox("with Salad"); 
        JCheckBox check3 = new JCheckBox("with Cake");
        panel2.add(check1);
        panel2.add(check2);
        panel2.add(check3);
        check1.addActionListener(this);
        check2.addActionListener(this);
   
        Container container = this.getContentPane();
        container.add(panel1,BorderLayout.WEST);
        container.add(panel2,BorderLayout.EAST);
        container.add(label,BorderLayout.SOUTH);
        
        this.pack();
        this.setVisible(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
 
    public void actionPerformed(ActionEvent e) {
        System.out.println("hello");
    }
 
    public static void main (String args[]) {
        JRadioButtonSample2 jrbs2 = new JRadioButtonSample2();
        jrbs2.initialize();
    }
    
 }


***軽減税率計算アプリ [#r66f1a41]

演習:

とあるレストランのランチは税別1,000円です。ランチにはオプションがあって、ドリンクを追加すると税別200円、サラダを追加すると税別300円、ケーキを追加すると税別500円です。全部追加すると税別2,000円です。この金額に消費税がかかります。消費税は、お店で食べると10%で、持ち帰りだと8%です。このレストランでアルバイトする友人のために、税込金額を計算するアプリを作ってあげることにしました。以下のように動くよう作ってください。

#ref(lunchcalc.png)

ヒント:

- ラジオボタンとチェックボックスはisSelected()メソッドで選択されているか否かを調べられます。選択されているとtrueが、非選択だとfalseが返ってきます。これを調べて代金を計算してください。
- 代金の結果はラベルに書きます。
- ラベルの内容はsetText()メソッドで書き換えられます

解答例:

 import java.awt.*;
 import javax.swing.*;
 import java.awt.event.*;
 
 public class LunchCalc extends JFrame implements ActionListener{
 
 	JLabel total = new JLabel("1000 yen");
         JRadioButton radio1 = new JRadioButton("for here");
         JRadioButton radio2 = new JRadioButton("to go");
 	JCheckBox check1 = new JCheckBox("with Drink");
         JCheckBox check2 = new JCheckBox("with Salad"); 
 	JCheckBox check3 = new JCheckBox("with Cake");
 
     public void initialize() {
         this.setTitle("Lunch Calc");
 
         JPanel panel1 = new JPanel();
         JPanel panel2 = new JPanel();
         
         total.setHorizontalAlignment(JLabel.CENTER);
         
         ButtonGroup group = new ButtonGroup();
         group.add(radio1);
         group.add(radio2);
     
         panel1.setLayout(new GridLayout(2,1));
         panel2.setLayout(new GridLayout(3,1));
     
         panel1.add(radio1);
         panel1.add(radio2);
 	radio1.addActionListener(this);
 	radio2.addActionListener(this);
     
         panel2.add(check1);
         panel2.add(check2);
         panel2.add(check3);
 	check1.addActionListener(this);
 	check2.addActionListener(this);
 	check3.addActionListener(this);
     
         Container container = this.getContentPane();
         container.add(panel1,BorderLayout.WEST);
         container.add(panel2,BorderLayout.EAST);
         container.add(total,BorderLayout.SOUTH);
 
         
         this.pack();
         this.setVisible(true);
         this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
     }
 
     public void actionPerformed(ActionEvent e) {
 	int price=1000;
 	if(check1.isSelected()) price += 200;
 	if(check2.isSelected()) price += 300;
 	if(check3.isSelected()) price += 500;
 	if(radio1.isSelected()) price *= 1.1;
 	if(radio2.isSelected()) price *= 1.08;
         String result=String.valueOf(price);
 	total.setText(result + " yen");
     }
 
     public static void main (String args[]) {
         LunchCalc lc = new LunchCalc();
         lc.initialize();
     }
     
 }

***項目をリストする [#m5682174]


コピペして動かしてみてください。

#ref(list.png)
 
 import java.awt.*;
 import javax.swing.*;
 
 public class JListSample extends JFrame {
 
        JListSample(String title) {
                setTitle(title);
                
                String[] data = {"Iced Coffee", "Iced Tea", "Blend Coffee"};
                
                 JList<String> list = new JList<String>(data);
                JScrollPane scroll = new JScrollPane(list);
                
                scroll.setPreferredSize(new Dimension(200,100));
 
                JPanel panel = new JPanel();
 
                Container container = getContentPane();
                container.add(scroll);
        }
 
        public static void main(String[] args) {
                JListSample sample = new JListSample("ListSample");
                sample.pack();
                sample.setVisible(true);
                sample.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
 }

***メニューバーを出す [#v6405eed]

http://gyazo.com/dd4e103c011682b3a78b9ed0c8d5134b.png


まずはシンプルなプルダウンメニューを作ってみましょう。
このプログラムは何もしません。

http://is.ocha.ac.jp/~siio/gyazo/JMenuSample1.png

 import java.awt.*;
 import javax.swing.*;
 import java.awt.event.*;
 
 public class JMenuSample extends JFrame implements ActionListener {
 	
 public void initialize() {
 	this.setTitle("MenuSample");
 	
 	JMenuBar menubar = new JMenuBar();
 	JMenu menu = new JMenu("menu");
 	
 	JMenuItem item1 = new JMenuItem("Sandwiches");
 	JMenuItem item2 = new JMenuItem("Side Orders");
 	JMenuItem item3 = new JMenuItem("Drinks");
 	
 	menu.add(item1);
 	menu.add(item2);
 	menu.add(item3);
 	
 	menubar.add(menu);
 	this.setJMenuBar(menubar);
 	
 	this.setSize(400,200);
 	this.setVisible(true);
 	this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
 
 public void actionPerformed(ActionEvent e){
 }
 
 public static void main(String[] args) {
 	JMenuSample sample = new JMenuSample();
 	sample.initialize();
 }
 
 }


メニューにはメニューを追加することもできます。
上でitem3をメニューに変更すると、これにitemを追加できます。

http://is.ocha.ac.jp/~siio/gyazo/JMenuSample2.png


 import java.awt.*;
 import javax.swing.*;
 import java.awt.event.*;
 
 public class JMenuSample extends JFrame implements ActionListener {
 	
 public void initialize() {
 	this.setTitle("MenuSample");
 	
 	JMenuBar menubar = new JMenuBar();
 	JMenu menu = new JMenu("menu");
 	
 	JMenuItem item1 = new JMenuItem("Sandwiches");
 	JMenuItem item2 = new JMenuItem("Side Orders");
 	JMenu item3 = new JMenu("Drinks");
 	
 	menu.add(item1);
 	menu.add(item2);
 	menu.add(item3);
 	
 	JMenuItem subitem1 = new JMenuItem("Iced Coffee");
 	JMenuItem subitem2 = new JMenuItem("Iced Tea");
 	item3.add(subitem1);
 	item3.add(subitem2);
 	
 	menubar.add(menu);
 	this.setJMenuBar(menubar);
 	
 	this.setSize(400,200);
 	this.setVisible(true);
 	this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
 
 public void actionPerformed(ActionEvent e){
 	}
 }
 
 public static void main(String[] args) {
 	JMenuSample sample = new JMenuSample();
 	sample.initialize();
 }
 
 }


それぞれのitemに、フレーム自身をaction Listenerとして登録すれば、イベントを受け付けることができます。
ここでは、メニューアイテムにcommandという情報をつけて、ActionPerformedではこれを使ってメニュー項目を区別しています。



 import java.awt.*;
 import javax.swing.*;
 import java.awt.event.*;
 
 public class JMenuSample extends JFrame implements ActionListener {
 	
 public void initialize() {
 	this.setTitle("MenuSample");
 	
 	JMenuBar menubar = new JMenuBar();
 	JMenu menu = new JMenu("menu");
 	
 	JMenuItem item1 = new JMenuItem("Sandwiches");
 	item1.addActionListener(this);
 	item1.setActionCommand("Sandwiches");
 	JMenuItem item2 = new JMenuItem("Side Orders");
 	item2.addActionListener(this);
 	item2.setActionCommand("Side Orders");
 	JMenu item3 = new JMenu("Drinks");
 	
 	menu.add(item1);
 	menu.add(item2);
 	menu.add(item3);
 	
 	JMenuItem subitem1 = new JMenuItem("Iced Coffee");
 	subitem1.addActionListener(this);
 	subitem1.setActionCommand("Iced Coffee");
 	JMenuItem subitem2 = new JMenuItem("Iced Tea");
 	subitem2.addActionListener(this);
 	subitem2.setActionCommand("Iced Tea");
 	item3.add(subitem1);
 	item3.add(subitem2);
 	
 	menubar.add(menu);
 	this.setJMenuBar(menubar);
 	
 	this.setSize(400,200);
 	this.setVisible(true);
 	this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
 
 public void actionPerformed(ActionEvent e){
 	String command = e.getActionCommand();
 	if(command != null){
 		System.out.println(command);
 	}
 }
 
 public static void main(String[] args) {
 	JMenuSample sample = new JMenuSample();
 	sample.initialize();
 }
 
 }



***演習:メニューを色々追加してみてください。(メニュー項目は何でも良いです) [#rba61398]

//演習ができそうにないという人は、飛ばして、次に進んでください。

http://gyazo.com/2d9c3b6534e7b87fcd3ec22be00d5fed.png

他のメニューの追加も試してみましょう。例えばお支払いメニュー。

http://is.ocha.ac.jp/~siio/gyazo/JMenuSample3.png

***Color Chooserを使う [#colorchooser]

次をコピペして動かしてみてください。色を選択するパネルが出ます。動作を確認してください。


 import java.awt.*;
 import javax.swing.*;
 import java.awt.event.*;
 
 public class JColorChooserSample extends JFrame implements ActionListener {
        JButton button;
 
        JColorChooserSample(String title){
                setTitle(title);
                button = new JButton("choose color");
                button.addActionListener(this);
 
                JPanel panel = new JPanel();
                panel.add(button);
                Container container = getContentPane();
                container.add(panel);
        }
 
        public void actionPerformed(ActionEvent e){
                JColorChooser colorchooser = new JColorChooser();
                Color color = colorchooser.showDialog(this,"choose a color",Color.blue);
                //button.setBackground(color);
                button.setForeground(color);
        }
 
        public static void main(String[] args){
                JColorChooserSample sample = new JColorChooserSample("JColorChooserSample");
                sample.pack();
                sample.setVisible(true);
                sample.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
 }


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