简体   繁体   中英

Stack overflow error GUI programming

I have a big problem i tried to solve it for days. I programmed a little program but it doesn't work.The error is Stackoverflow I already searched this website on and on again .I broke it down to the part wich doesn't works so here is the code. This is the frame:

package snippet;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class MyFrame extends JFrame {   

  JButton button;
  JLabel label;
  TextEdit textEdit = new TextEdit();

    public void LetsGo() {

    setBounds(0, 0, 800, 510);
    setVisible(true);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setTitle("Game");
    setResizable(false);
    setLocationRelativeTo(null);

    //Labels

    label = new JLabel();
    label.setText("Change Me");
    label.setBounds(30, 25, 200, 50);
    label.setVisible(true);
    add(label);

    button = new JButton();
    button.setText("I Will Change A Text");
    button.setBounds(30, 130, 200, 400);
    button.addActionListener(new Listener());;
    add(button);        
}
    public class Listener implements ActionListener {                       

        @Override
        public void actionPerformed(ActionEvent e) {
            textEdit.editTheText();
        }
    }

And this object should edit the Text :

    package snippet;

public class TextEdit {
    MyFrame frame = new MyFrame();
    public void editTheText(){
        frame.label.setText("Text was edited");
    }
}

So the real code is much more complex so i won't put all in one Object Would be great if i receive some help would be very very thankful for that

You are creating a new MyFrame in TextEdit , which I don't think is what you want to do because frame.label will be null .

What you really should be doing is assigning the JFrame inside of Listener .

public class Listener implements ActionListener {

   private JFrame frame;

   public Listener(JFrame frame) {
       this.frame = frame;
   }                      

    @Override
    public void actionPerformed(ActionEvent e) {
        if (this.frame.label != null) {
            this.frame.label.setText("Text was edited");
        }
    }
}

Then for the the other code, you don't have a constructor or your actual class is called LetsGo ?

Assuming it is not called LetsGo and it actually is MyFrame , you need an actual constructor.

public MyFrame() {
    LetsGo();
}

Then in the LetsGo method, add the frame to the Listener

button.addActionListener(new Listener(this));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM