Reputation: 291
I have a JTextField and a button in a class called Main. I have an ActionListener in another class called Action. I want the ActionListener to be able to refrence the JTextField. I keep getting a null pointer exception. I want to keep the JTextField and ActionListener seperate. I am going to be having many ActionListeners and it would be easier for me to organize it this way.
public class Main {
public JTextField text;
public JTextField getText(){
return this.text;
}
public static void main(String[] args) {
Main main=new Main();
main.blah();
}
public void blah(){
JFrame myWindow=new JFrame("ff");
myWindow.setSize(500,500);
myWindow.setVisible(true);
myWindow.setDefaultCloseOperation(3);
text=new JTextField(10);
JLabel lengthL = new JLabel("Enter a number",SwingConstants.CENTER );
JButton button=new JButton("Click button");
myWindow.getContentPane();
myWindow.setLayout(new GridLayout(4,4));
myWindow.add(lengthL);
myWindow.add(text);
myWindow.add(button);
Action hand=new Action();
button.addActionListener(hand);
}
}
public class Action implements ActionListener{
@Override
public void actionPerformed(ActionEvent e) {
Main main=new Main();
double length=Double.parseDouble(main.text.getText());
System.out.println(length);
}
}
Upvotes: 0
Views: 1456
Reputation: 54806
Why not pass the JTextField when you create the ActionListener, like so:
public class Action implements ActionListener{
private JTextField text;
public Action(JTextField text) {
this.text = text;
}
@Override
public void actionPerformed(ActionEvent e) {
double length=Double.parseDouble(text.getText());
System.out.println(length);
}
}
//in Main:
public void blah(){
JFrame myWindow=new JFrame("ff");
myWindow.setSize(500,500);
myWindow.setVisible(true);
myWindow.setDefaultCloseOperation(3);
text=new JTextField(10);
JLabel lengthL = new JLabel("Enter a number",SwingConstants.CENTER );
JButton button=new JButton("Click button");
myWindow.getContentPane();
myWindow.setLayout(new GridLayout(4,4));
myWindow.add(lengthL);
myWindow.add(text);
myWindow.add(button);
Action hand=new Action(text); //change this line
button.addActionListener(hand);
}
Upvotes: 2
Reputation: 199215
I keep getting a null pointer exception
That's because you're creating a new Main
instance when you handle the event:
public void actionPerformed(ActionEvent e) {
Main main=new Main();
...
You should better have the action a reference of the container class ( Main ) and a method to access that textfield value:
Main aMain;
public void actionPerformed(ActionEvent e) {
this.aMain.getText();
....
Or even better:
public void actionPerformed(ActionEvent e) {
double lenght = this.main.getValue();// returns double
...
Upvotes: 1