//cd c:\HPBasic\Toppage-sample3\MySwing //javac ColorPane.java //set CLASSPATH=. //appletviewer ColorPane.java import java.applet.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; /* */ public class ColorPane extends JApplet { public void init(){ Container contentPane = getContentPane(); ColorPanel panel = new ColorPanel(); contentPane.add(panel); } } class ColorPanel extends JPanel implements ActionListener { JButton yellowB; JButton blueB; JButton redB; public ColorPanel() { yellowB = new JButton("Yellow"); blueB = new JButton("Blue"); redB = new JButton("Red"); add(yellowB); add(blueB); add(redB); yellowB.addActionListener(this); blueB.addActionListener(this); redB.addActionListener(this); } public void actionPerformed(ActionEvent event) { Color c; Object source = event.getSource(); // String source = event.getActionCommand(); if (source == yellowB) { c=Color.yellow; } else if (source == blueB) { c=Color.blue; } else { c=Color.red; } setBackground(c); } } /* 1 「core Java」P375のmainプログラムをアプレットに書き換える。 2 JPanelバネルにボタンを貼り付け、背景色を変える操作を別クラスとし、 class ColorPanel extends JPanel とするのは、「独習1Java」のAWT利用、Canvasへの 描画の例(P450)にはあったが、それにimplements ActionListenerとし、 ボタンの貼り付けも単に、add(yellowB)でいいというのは驚いた。 3 ボタンのレイアウトに、GridLayoutを指定すると、ボタンが異常に大きくなる。 4 Object source = event.getSource(); の方が下記よりりいいとある。 String source = event.getActionCommand(); 5 setBackground(c) は、Componentクラスのメソッド。 6 なお、 ColorLabel.java JLabelにはボタンがはりつかない。 */