首页 文章

JPanels之间的沟通

提问于
浏览
0

我有一个JPanel类,它创建了panel1和panel2 . Panel1和Panel2各有一个按钮 . 我想要完成的是当我点击Panel1中的按钮时,它会更新Panel2中的按钮 . 我必须这样做而不改变Panel2中的任何内容 . 基本上我必须让Panel1有一种方法来跟踪Panel2的实例,我必须通过JPanel类来做到这一点 . 但我不知道在哪里开始甚至完成这个 .

myJPanel.java

import java.awt.*;
import javax.swing.*;

public class myJPanel extends JPanel
{
public myJPanel()
{
    super();
    setBackground(Color.gray);

    setLayout(new BorderLayout());

    myJPanel1 p1 = new myJPanel1();
    add(p1,"North");
    myJPanel2 p2 = new myJPanel2();
    add(p2,"Center");



}
}

myJPanel1.java

import java.awt.*;
import javax.swing.*;

public class myJPanel1 extends JPanel
{

public myJPanel1()
{
    super();
    setBackground(Color.yellow);

    student st1 = new student("Clark","Fontaa",26);
    // the whatsUp of this student has to shown in the other panel

    JButton jl1 = new JButton(st1.getInfo());
    add(jl1);
}
}

myJPanel2.java

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

public class myJPanel1 extends JPanel implements ActionListener
{

student st1 = new student("Fred","Fonseca",44);
JButton jl1;
public myJPanel1()
{
    super();
    setBackground(Color.yellow);

    jl1 = new JButton(st1.getInfo());
            jl1.addActionListener(this);
    add(jl1);
}

    public void actionPerformed(ActionEvent event){
        Object obj = event.getSource();
        if (obj == jl1){
        // something here
        }
    }

谢谢你的帮助!

1 回答

  • 0

    在Panel类型的myJPanel1类中添加一个新字段,以便您可以参考Jpanel2,这样您就可以在不更改Panel 2中的任何内容的情况下进一步使用它 . 请按照下列步骤操作:

    • 添加名为Panel panel2的新字段,并在构造函数中添加Panel参数,如 myJPanel1(JPanel panel) {//set local panel2 instance variable now}

    • myJPanel 类中,更改以下内容:

    myJPanel1 p1 = new myJPanel1();
    add(p1,"North");
    myJPanel2 p2 = new myJPanel2();
    add(p2,"Center");
    

    myJPanel2 p2 = new myJPanel2();
    add(p2,"Center");
    myJPanel1 p1 = new myJPanel1(p2);//reverse the order of panel instantiation and pass p2 to panel1.
    add(p1,"North");
    
    • 现在你在p1中引用了p2,如果你有任何你喜欢的话 .

    • 使用equals方法进行比较而不是 ==

相关问题