I was just trying to code stuff for fun, however I am stuck. I am trying to create 3 JButtons in one class A, and then call those buttons in another class B and then add ActionListeners in class B. So basically I only create the buttons in abstract class A and then call them in class B which extends class A and in class B I do stuff with those buttons. It sounds very simple, however I can't figure this out.
In class 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);
}
In class 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;
However this gave me a nullpointerexception. Thanks in advance!
Edit: I know my problem is the exception, I just don't know how to fix it :( Could someone please write some quick pseudocode for me how to create a button in one class and call that button in another? :)