ActionListner和ActionPerformed返回类外的动作

时间:2016-02-21 00:22:28

标签: java string swing

我在这个类之外创建了一个jpanel,它有一个按钮,我希望执行以下操作也可以传递。我是编程新手,不知道怎么做。无法在线寻求帮助。 b2.setText(b)中;

(defroutes app
  (ANY [":path" :path #".*"] [path]
       {:status 200
        :headers {"Content-Type" "text/plain"}
        :body (str "path = " path)}))

import java.awt。; import javax.swing。;

公共类myJPanel2扩展了JPanel {

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

public class myJPanel1 extends JPanel implements ActionListener
{
        String b = "a";
    JButton jl1;

    public myJPanel1(student st1, myJPanel2 b2)
    {

                super();

        setBackground(Color.yellow);
        //JButton jl1 = new JButton(st1.getInfo());
        jl1 = new JButton(st1.getInfo());
                jl1.addActionListener(this);
                add(jl1);

    }

   @Override
        public void actionPerformed(ActionEvent e) {
        double r = Math.random();
        int myNumber = (int)(r*3f);
        if (myNumber == 0){ 

            b = "reading";

        }
        if (myNumber == 1){ 

            b = "talking";

        }
        if (myNumber == 2){ 
            b = "interacting";

            b2.setText(b);

        } 

    }     
}

}

2 个答案:

答案 0 :(得分:2)

JPanel没有setText()方法,因此您无法在面板上设置文本。

也许您正在尝试设置按钮的文本。在这种情况下,您需要将JButton定义为实例变量。然后在该变量上调用setText(),而不是在面板上调用。

//myJPanel2 b2;
JButton jl1;

...

//JButton jl1 = new JButton(st1.getInfo());
jl1 = new JButton(st1.getInfo());

...

//b2.setText(b);//this doesn´t work   
jl1.setText(b);

答案 1 :(得分:0)

您可以在按钮上设置文字,但不能重新绘制它。致电revalidate();,然后致电repaint();设置文本后。