解答例 - 実習課題1 - 3.イベント・ハンドラ
(実習課題1)
以下のサンプルプログラムを作成しなさい。
- フレームに含まれるコンポーネントはラジオボタン(JRadioButton)3つ・ボタン(JButton)とラベル(JLabel)1つ。表示するテキストと配置は任意。
- 3つラジオボタンは同時に複数選択できないものとする。
- 1つのボタンが押されると、選択されているラジオボタンに対応するテキストをラベルに表示する。
- (ヒント)ボタンが押されたときに、各ラジオボタンの状態を調べる。
解答例
package com.techscore.ui.chapter3.exercise1;
/**
* SampleFrame.java
* TECHSCORE Javaユーザインタフェース3章 実習課題1
*
* Copyright (c) 2004 Four-Dimensional Data, Inc.
*/
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JRadioButton;
public class SampleFrame extends JFrame implements ActionListener {
private JLabel label;
private JRadioButton eastButton;
private JRadioButton centerButton;
private JRadioButton westButton;
public SampleFrame() {
super("SampliFrame");
setDefaultCloseOperation(EXIT_ON_CLOSE);
label = new JLabel("label");
getContentPane().add(label, BorderLayout.NORTH);
//ボタングループの作成
ButtonGroup group = new ButtonGroup();
//ボタングループにラジオボタンを3つ追加
//さらに、そのボタンをフレームのContent Paneに追加
eastButton = new JRadioButton("right");
group.add(eastButton);
getContentPane().add(eastButton, BorderLayout.EAST);
centerButton = new JRadioButton("center");
group.add(centerButton);
getContentPane().add(centerButton, BorderLayout.CENTER);
westButton = new JRadioButton("left");
group.add(westButton);
getContentPane().add(westButton, BorderLayout.WEST);
JButton button = new JButton("action");
getContentPane().add(button, BorderLayout.SOUTH);
button.addActionListener(this);
pack();
}
public void actionPerformed(ActionEvent event) {
if (eastButton.isSelected()) {
label.setText("right");
} else if (centerButton.isSelected()) {
label.setText("center");
} else if (westButton.isSelected()) {
label.setText("left");
}
}
public static void main(String args[]) {
new SampleFrame().setVisible(true);
}
}

