I'm a beginner and I wrote this code but it doesn't seem to work. I run the code and the frame doesn't appear idk why.
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());
}}
I also have a main method:
public class másolgatóHasználata {
public static void main(String args[]){
new főMásolgató();
}}
(the class names are in hungarian dont watch)
CodePudding user response:
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());
}
}
CodePudding user response:
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.