我只是在尝试编写有趣的代码,但是我被卡住了。 我试图在一个类A中创建3个JButton,然后在另一个类B中调用这些按钮,然后在类B中添加ActionListeners。所以基本上,我只在抽象类A中创建按钮,然后在扩展类的类B中调用它们A和BI类中的东西用这些按钮填充。听起来很简单,但是我无法弄清楚。
A类:
public abstract class Activity implements ActionListener {
public static JFrame frame;`
public static JPanel panel;
public static JLabel label;
public JButton buttonleft;
public JButton buttonmid;
public JButton buttonright;
protected void makenButtons(String textlinks, String textmidden, String textrechts) {
JButton buttonleft = new JButton(textlinks);
JButton buttonmid = new JButton(textmidden);
JButton buttonright = new JButton(textrechts);
panel.add(buttonleft);
panel.add(buttonmid);
if (textrechts!=null) {
panel.add(buttonright);
}
B类:
package hi;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JPanel;
public class MainActivity extends Activity{
public static void main(String[] args) {
Activity.makenFrame(380,120,"Choose mode");
Activity.makenLabel("Choose a work mode: ");
Activity.makenOpties("Run as server", "Run as client");
//Activity.makenButtons("Start","Exit",null);
MainActivity a = new MainActivity();
a.actiesButtons("Start","Exit");
Activity.toevoegenpanel();
}
public void actiesButtons(String textleft, String textright) {
JButton buttonleft = super.buttonleft;
JButton buttonmid = super.buttonmid;
buttonleft.setText(textleft);
buttonmid.setText(textright);
buttonleft.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == buttonleft) {
System.out.print("Hi");
}
}
});
buttonmid.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
if (event.getSource() == buttonright) {
System.exit(0); }
}
});
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
I deleted some not-important stuff. So basically I just like to know how to call the JButtons in class B. I tried:
JButton buttonleft = super.buttonleft;
JButton buttonmid = super.buttonmid;
但是这给了我一个nullpointerexception。 预先感谢!
编辑:我知道我的问题是例外,我只是不知道如何解决它:( 有人可以为我写一些快速的伪代码,如何在一个类中创建一个按钮,在另一个类中调用该按钮吗? :)