通信,类和ActionListener

时间:2014-10-13 23:52:20

标签: java actionlistener

我是java的新手,我想知道是否有人可以帮助我

我有三个面板(myJPanel,myJPanel1,myJPanel2),其中myJPanel1将显示学生的名字myJPanel2将显示我的方法。对于我的任务,我只能在myJPanel中对我的代码行进行一次更改,myJPanel2中会有很多更改。

我知道对于我必须在myJPanel中更改的一行代码,我必须能够将p1传递给我将修改大部分代码的类。我不确定该怎么做。我得到了一个提示,我只需要在这行代码中添加两个字母,它就可以工作了,我已多次尝试并失败了。

我想如果我能弄清楚如何做到这一点,我可以让ActionListener在myJPanel2中工作

到目前为止,这是我的代码(我知道有很多评论,但这些只是帮助我自己编写代码的注释)。

myJPanel

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

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

        setLayout(new BorderLayout());

        myJPanel1 p1 = new myJPanel1();
        myJPanel2 p2 = new myJPanel2();
        //change above line(add two letters)
        //Constructor is gateway for passing information into another class
        //When passing in a value, you have access in the constructor

        add(p1,"North");
        add(p2,"Center");                   

    }
}

myJPanel2

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

 public abstract class myJPanel2 extends JPanel implements ActionListener
 {
    //Modify button on myJPanel1 and capture buttons that has been pressed
    //Have to modify myJPanel to access fields and attributes that need access
    //From myJPanel2 makes changes so listen to button events on myJPanel1
    //Get access to button on myJPanel1, set it equal to student

    JButton b2;
    JButton b1;
    student st1;

    public myJPanel2()
    {
        super();
        st1 = new student("Fred","Fonseca",44);
        setBackground(Color.pink);
        b2 = new JButton("whats Up will be shown here" );
        add(b2);

        b1.addActionListener(this);
    }

    public void actionPerformed(ActionListener event)
    {
        Object obj = event.getSource();
        if(obj == b1)
        {
            b2.setText(st1.whatsUp());
        }
    }

}

0 个答案:

没有答案