私は過去の紙試験問題を修了しており、中央に緑色の四角形を表示するアプレットを作成するよう質問します。+
,-
およびreset
ですが、どのボタンがクリックされたときでも、どのボタンが押されたのかを本質的に把握する必要があります。私はあなたがe.getSource()
を使用することを知っていますが、私はこれについてどうやって行くのか分かりません。単一のボタンハンドラオブジェクトを提供する方法
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Square extends JApplet {
int size = 100;
public void init() {
JButton increase = new JButton("+");
JButton reduce = new JButton("-");
JButton reset = new JButton("reset");
SquarePanel panel = new SquarePanel(this);
JPanel butPanel = new JPanel();
butPanel.add(increase);
butPanel.add(reduce);
butPanel.add(reset);
add(butPanel, BorderLayout.NORTH);
add(panel, BorderLayout.CENTER);
ButtonHandler bh1 = new ButtonHandler(this, 0);
ButtonHandler bh2 = new ButtonHandler(this, 1);
ButtonHandler bh3 = new ButtonHandler(this, 2);
increase.addActionListener(bh1);
reduce.addActionListener(bh2);
reset.addActionListener(bh3);
}
}
class SquarePanel extends JPanel {
Square theApplet;
SquarePanel(Square app) {
theApplet = app;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.green);
g.fillRect(10, 10, theApplet.size, theApplet.size);
}
}
class ButtonHandler implements ActionListener {
Square theApplet;
int number;
ButtonHandler(Square app, int num) {
theApplet = app;
number = num;
}
public void actionPerformed(ActionEvent e) {
switch (number) {
case 0:
theApplet.size = theApplet.size + 10;
theApplet.repaint();
break;
case 1:
if (theApplet.size > 10) {
theApplet.size = theApplet.size - 10;
theApplet.repaint();
}
break;
case 2:
theApplet.size = 100;
theApplet.repaint();
break;
}
}
以下のサンプルのような場合は、else文を使用することができます私は場合は、 'e.getSourceを()'使うべきとは思いません(匿名クラスを使用して)ボタンごとに異なるリスナーを使用すると、ソースをまったく確認する必要はありません。 –
Jornの提案は、よりメンテナンス性とモジュール性が高いので、間違いなく好ましい方法です。 –