0

パネル 1 のボタン 1 をクリックし、パネル 2 のボタン 2 の情報を変更する必要がある割り当てがありますが、情報を渡す方法がわかりません。

メソッド b() からの情報を panel2 から one に戻すことができるかもしれないと思っていましたが、うまくいきません。

私はかなり行き詰まっており、プログラムを進める方法がわかりません。どんな助けでも大歓迎です。

パネル1

public class MyJPanel1 extends JPanel implements ActionListener {
    Student st1 = new student("Fred","Fonseca",44);

    JButton j = new JButton(st1.getInfo());
    JButton b1 = new JButton("..");

    public myJPanel1() {
        super();
        setBackground(Color.yellow);
        // the whatsUp of this student has to shown in the other panel
        j.addActionListener(this); 
        add(j);         
    }   
    public void actionPerformed(ActionEvent event) {         
        Object obj = event.getSource();
        //=====================================                            
            if (obj == j){
                b1.setText(st1.whatsUp()); // Output on JButton in JPanel2 
            }
        }
    }
 }

パネル2

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class myJPanel2 extends JPanel {
    JButton j1 = new JButton("");

    public void b(JButton b1) {
        JButton j1 = b1;            
    }   
    public myJPanel2() {
        super();
        setBackground(Color.pink);
        setLayout(new GridLayout(3,1));
        add(j1);
        // j1.setText(b1);
    }

 }
4

3 に答える 3

0

注意すべき点がいくつかあります。Java はオブジェクト指向言語です。つまり、クラスを使用してオブジェクトを定義し、それらのオブジェクトを可能な限り再利用します。2 つのパネルがあり、それぞれにボタンが含まれている場合は、クラスを 1 回定義するのに最適な時期です。

public class MyPanel extends JPanel{
  protected JButton button;

  public MyPanel(String buttonName){
    button = new JButton(buttonName);
  }
  //etc etc etc
}

そして、クラスを何度も使用します

public class MyProgram {
  protected MyPanel panel1;
  protected MyPanel panel2;

  public MyProgram(){
    panel1 = new MyPanel("Button 1");
    panel2 = new MyPanel("Button 2");
  }
  //etc etc
}

プログラムをこのようにセットアップすると、2 つのパネル間の通信が非常に簡単になります。これは、MyProgramでパネルの両方のインスタンスが使用できるためです。

したがって、MyPanelクラスにsetButtonTextというメソッドがあったとしましょう。

public void setButtonText(String text){
  button.setText(text);
}

ボタンの 1 つのテキストを変更するために、 MyProgramでこのメソッドを呼び出すことができます。

myPanel1.setText("New Button 1 text");

しかし、 myPanel1またはmyPanel2のボタンが押されたかどうかは、どうすればわかりますか? Java がActionListenerを使用して異なるオブジェクト間でイベントを通信する方法を調べることができます。

幸運を!

于 2013-09-30T18:27:38.177 に答える