改变不同面板的按钮

时间:2015-09-29 01:33:56

标签: java class jpanel jbutton

我需要帮助弄清楚如何在MyJPanel2中更改Button b2。我无法对MyJPanel2进行任何更改。

  • p1(代表myJPanel1的变量)需要操作位于p2的按钮(代表myJPanel2的变量)。
  • 为了做到这一点,p1(代表myJPanel1的变量)需要接收p2(代表myJPanel2的变量)。
  • 哪个对象/类可以访问myJPanel1和myJPanel2?
  • 这是将对象(信息)发送给另一个对象的最佳位置,使用新语句并发送参数。

除了我不知道如何从MyJPanel1到达MyJPanel2中的b2之外我一切正常。

public class MyJFrame extends JFrame
{
    public MyJFrame ()
    {
        super ("Name - Assignment 05");

        MyJPanel mjp = new MyJPanel();

        getContentPane().add(mjp,"Center");


        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setSize (640, 480);
        setVisible(true);
    }
}
--------------
public class MyJPanel extends JPanel
{;

    public MyJPanel()
    {
        super();
        setBackground(Color.gray);

        setLayout(new GridLayout(2, 1));

MyJPanel2 p2 = new MyJPanel2();            
MyJPanel1 p1 = new MyJPanel1(p2);


        add(p1,"North");
        add(p2,"Center");
    }
}
----------------
public class MyJPanel1 extends JPanel implements ActionListener
{
    JButton jl1, j2, b2;
    Student st1;

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

        st1 = new Student("Bill","Gates",56);
        // the whatsUp of this student has to shown in the other panel

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

        b2 = new JButton(st1.whatsUp());
        add(b2);
    }
    //=====================================
    public void actionPerformed(ActionEvent event) {
        Object obj = event.getSource();
        //=====================================
        if (obj == jl1) {
            String b = st1.whatsUp();
            b2.setText("               " + b + "               ");
        }
    }
}
-----------------
public class MyJPanel2 extends JPanel
{
    //==================================================
    //no changes allowed in myJPanel2 for assignment 05
    //==================================================
    JButton b1,b2,b3,b4;

    public MyJPanel2()
    {
        super();
        setBackground(Color.pink);
        //setLayout(new GridLayout(5,1));
        b1 = new JButton("When the user clicks on the button in the UPPER panel" );
        add(b1);

        b2 = new JButton("Display here whatsUp from the student in UPPER Panel" );
        add(b2);

        b3 = new JButton("===>>>>You CANNOT create a student here <======" );
        add(b3);

        b4 = new JButton("It has to be the student from the UPPER Panel" );
        add(b4);
    }
}

0 个答案:

没有答案