解答例 - 実習課題3 - 3.イベント・ハンドラ
(実習課題3)
以下のサンプルプログラムを作成しなさい。
- フレームに含まれるコンポーネントはラベル(JLabel)2つとメニュー。メニューには通常のメニューアイテム(JMenuItem)3つとラジオボタンメニューアイテム(JRadioButtonMenuItem)2つ。メニューのテキストおよび配置は任意。
- ラジオボタンメニューは同時に1つしか選択できないようにする。
- 1つのラベルにはメニューアイテムが選択されたときに対応するテキストを表示する。もう1つのラベルには選択されているラジオボタンメニューに対応するテキストを表示する事。
- (ヒント)メニューアイテムには「java.awt.event.ActionListener」を使用する。
- (ヒント)ラジオボタンメニューアイテムには「java.awt.event.ItemListener」を使用する。
解答例
package com.techscore.ui.chapter3.exercise3;
/**
* SampleFrame.java
* TECHSCORE Javaユーザインタフェース3章 実習課題3
*
* Copyright (c) 2004 Four-Dimensional Data, Inc.
*/
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.ButtonGroup;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;
public class SampleFrame extends JFrame implements ActionListener, ItemListener {
private JLabel label1;
private JLabel label2;
private JMenuItem redMenu;
private JMenuItem yellowMenu;
private JMenuItem greenMenu;
private JRadioButtonMenuItem boyRadioButton;
private JRadioButtonMenuItem girlRadioButton;
public SampleFrame() {
super("SampleFrame");
setDefaultCloseOperation(EXIT_ON_CLOSE);
label1 = new JLabel("label");
getContentPane().add(label1, BorderLayout.WEST);
label2 = new JLabel("label2");
getContentPane().add(label2, BorderLayout.EAST);
//MenuBarの作成
JMenuBar menuBar = new JMenuBar();
super.setJMenuBar(menuBar);
//Menuを作成
JMenu fileMenu = new JMenu("Signal");
menuBar.add(fileMenu);
redMenu = new JMenuItem("red");
fileMenu.add(redMenu);
redMenu.addActionListener(this);
yellowMenu = new JMenuItem("yellow");
fileMenu.add(yellowMenu);
yellowMenu.addActionListener(this);
greenMenu = new JMenuItem("green");
fileMenu.add(greenMenu);
greenMenu.addActionListener(this);
//Radioボタン用Menuの作成
JMenu radioButtonMenu = new JMenu("Human");
menuBar.add(radioButtonMenu);
ButtonGroup group = new ButtonGroup();
boyRadioButton = new JRadioButtonMenuItem("boy");
group.add(boyRadioButton);
radioButtonMenu.add(boyRadioButton);
boyRadioButton.addItemListener(this);
girlRadioButton = new JRadioButtonMenuItem("girl");
group.add(girlRadioButton);
radioButtonMenu.add(girlRadioButton);
girlRadioButton.addItemListener(this);
pack();
}
public void actionPerformed(ActionEvent event) {
if (event.getSource() == redMenu) {
label1.setText("Stop!");
} else if (event.getSource() == yellowMenu) {
label1.setText("Caution!");
} else if (event.getSource() == greenMenu) {
label1.setText("Go!");
}
}
public void itemStateChanged(ItemEvent item) {
if (boyRadioButton.isSelected()) {
label2.setText("Boy");
} else if (girlRadioButton.isSelected()) {
label2.setText("Girl");
}
}
public static void main(String args[]) {
new SampleFrame().setVisible(true);
}
}

