質問

私はこれらの線に沿って何かを使用して、JavaでGUIを作ろうとしています。

public class GUIApp
{
    DrawingPanel dp;
    buttonPanel bp;
    ova = Oval;
 public GUIApp()
    {
        JFrame win = new JFrame("Drawing App");
        dp = new DrawingPanel();
        bp = new buttonPanel(this);

    //Settings for panels and frame

        ova = new Oval(100,100,100,100);

      }
      public void setOval(int c){
        //Change color of oval
      }
  }

それから、私のbuttonpanelクラスで私はこれを持っています:

public class ButtonPanel extends JPanel
{

    private JButton btnRed, btnGreen, btnBlue;

    public ButtonPanel(GUIApp d)
    {

        ButtonListener listener = new ButtonListener();
        btnRed = new JButton("Red");
        btnGreen = new JButton("Green");
        btnBlue = new JButton("Blue");

        btnRed.addActionListener(listener);
        btnGreen.addActionListener(listener);
        btnBlue.addActionListener(listener);

        setBackground(Color.lightGray);
        GridLayout grid = new GridLayout(3,1);
        add(btnRed,grid);
        add(btnGreen,grid);
        add(btnBlue,grid);
    }

    private class ButtonListener implements ActionListener{

        public void clickButton(ActionEvent event) {
            Object location = event.getSource();
            if (location == btnRed){
                d.setOval(1);
            }
            else if(location == btnGreen){
                d.setOval(2);
            }
            else if(location == btnBlue){
                d.setOval(3);
        }
        }

}
}

しかし、NetBeansは内側のButtonListenerクラスのエラーを提供しますが、その理由はわかりません。また、そのクラス内からGuiappクラスまで瀬戸を正しく呼び出す方法もわかりません。私は何が間違っているのですか?

役に立ちましたか?

解決

問題は、実装するときです ActionListener メソッドを定義する必要があります actionPerformed(ActionEvent e);あなたはあなたの中でそれをしていません ButtonListener クラス。あなたが望むものは何でもメソッドに名前を付けることはできません(あなたがしたように clickButton)、したがって、名前を変更するだけです clickButton 方法 actionPerformed (先に進んで追加します @Override 注釈も)。

電話するために今 d.setOval あなたの内側のクラス内から、 d 範囲内にある必要があります actionPerformed メソッドが呼び出されます。これを達成する方法はいくつかあります:あなたは作ることができます d クラスのメンバー変数、またはあなたがあなたのクラスを定義することができます ButtonListener 匿名のクラスとして。

たとえば、保存した場合 d メンバー変数として、あなたのコードは次のようになります:

public class ButtonPanel {
 private GUIApp d;

 public ButtonPanel(GUIApp d) {
  this.d = d;
  // The rest of your code here...
 }
}

または、次のような匿名クラスを使用できます。

public ButtonPanel(GUIApp d) {
 ActionListener listener = new ActionListener(){
  @Override
  public void actionPerformed(ActionEvent event) {
   Object location = event.getSource();
   if (btnRed.equals(location)) {
    d.setOval(1);
   } else if (btnGreen.equals(location)) {
    d.setOval(2);
   } else if (btnBlue.equals(location)) {
    d.setOval(3);
   }
  }
 };
 // The rest of your constructor code here ...
}

ノート: 私もどのように使用を変更したかに注目してください ==equals() オブジェクトの平等の場合。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top