javaswingjframeawtactionlistener

JFrame doesn't appear with ActionListener


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ó();
    }
}

Solution

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

    In your case, if you want to create an instance of főMásolgató, you need to invoke the default no-arg constructor defined by Java, instead of the void method főMásolgató.

    Here is an example with your code tweaked:

    public class főMásolgató implements ActionListener {
    
        JButton b;
        JLabel label;
        JTextField tfield;
        JFrame frame;
    
        // this is still a no-arg constructor, but unlike in your code,
        // this is defined by you, and not automatically 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());
        }
    }