2.2. ボタン
この節ではボタンをウィンドウに追加します。
import javax.swing.*; import java.awt.BorderLayout; public class ButtonFrame extends JFrame{ public ButtonFrame(){ super("button frame"); setDefaultCloseOperation(EXIT_ON_CLOSE); JLabel label=new JLabel("This is a label"); getContentPane().add(label,BorderLayout.CENTER); JButton button=new JButton("button"); getContentPane().add(button,BorderLayout.SOUTH); pack(); } public static void main(String args[]){ new ButtonFrame().setVisible(true); } }
基本的な方法はラベルの追加と同じです。アイコンを含んだボタンを追加する事もできます。ボタンを押したときの動作の指定については、後の章で説明します。

(実習課題2)
サンプルプログラムを改良しなさい。
- ボタンにアイコンを含ませる事。
- ボタンのサイズをアイコンのちょうど2倍になるようにする事。
- (ヒント)「setPreferredSize」メソッドを使用する。