JFrame doesn't appear with ActionListener

Viewed 41

I'm a beginner and I've written this code but it does not seem to work. I've run the code and for some reasons the JFrame does not appear (the class name is in Hungarian, do not mind it).

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

public class főMásolgató implements ActionListener {

    JButton b;
    JLabel label;
    JTextField tfield;
    JFrame frame;

    public void főMásolgató(){
        frame = new JFrame();
        b = new JButton("Másolás");
        label = new JLabel("");
        tfield = new JTextField();
        frame.add(b);
        frame.add(label);
        frame.add(tfield);
        b.addActionListener(this);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        label.setText(tfield.getText());
    }
}

public class másolgatóHasználata {
    public static void main(String args[]){
        new főMásolgató();
    }
}
2 Answers

The void method főMásolgató is not the class constructor.

When you instance a new főMásolgató you're simply invoking the default no-args constructor instead of the void method főMásolgató where you show your JFrame.

You should re-write it like this:

public class főMásolgató implements ActionListener {

    JButton b;
    JLabel label;
    JTextField tfield;
    JFrame frame;

    //This is now YOUR no-args constructor not the default one provided by Java
    public főMásolgató(){
        frame = new JFrame();
        b = new JButton("Másolás");
        label = new JLabel("");
        tfield = new JTextField();
        frame.add(b);
        frame.add(label);
        frame.add(tfield);
        b.addActionListener(this);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        label.setText(tfield.getText());
    }
}

Your mistake is that

public void főMásolgató(){ ... }

is a function not a constructor.

Your code will work if you do:

public class másolgatóHasználata {
  public static void main(String args[]){
    new főMásolgató().főMásolgató();
  }}

because here he will use the default constructor. then he will call your function. Or you can fix it by changing:

public void főMásolgató(){ ... }

to

public főMásolgató(){ ... }

Then your block is the constructor.

Hint: you can debug this by running line by line. This will let you know if your block was run or not.

Related