2016-07-28 3 views
0

私は過去の紙試験問題を修了しており、中央に緑色の四角形を表示するアプレットを作成するよう質問します。+,-および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; 
    } 
} 
+2

以下のサンプルのような場合は、else文を使用することができます私は場合は、 'e.getSourceを()'使うべきとは思いません(匿名クラスを使用して)ボタンごとに異なるリスナーを使用すると、ソースをまったく確認する必要はありません。 –

+0

Jornの提案は、よりメンテナンス性とモジュール性が高いので、間違いなく好ましい方法です。 –

答えて

0

現在のコードに基づいていますが、オブジェクト参照を比較するのに最適な方法ではありません。ボタンへの参照を渡すか、別の方法でアクセスする必要があります。例えば

if(e.getSource() == increase) { \\do something on increase} 

もう1つの方法は、ボタンの文字列を確認することです。

if(((JButton)e.getSource()).getText().equals("+")){ \\do something on increase} 

は、Java 8でのswitch文で文字列を使用できますが、Javaの7以下を使用している場合、それはifの文である必要があります。

0

あなたは

  if(e.getSource()==bh1){ 
        //your codes for what should happen 
      }else if(e.getSource()==bh2){ 

      }else if(e.getSource()==bh3){ 

      }else if(e.getSource()==bh4){ 
      } 

ORでもスイッチのcase文で

関連する問題