0

i have created a button which is supposed to add "label" to my frame but it just doesn't work it prints "starting..." but not adds the "label" Here's my code

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

public class NameHere extends JFrame implements ActionListener {
JButton button = new JButton("Start");
JLabel label = new JLabel("Starting the App");
NameHere() {

    button.setBounds(212,235,75,30);
    button.addActionListener(this::actionPerformed);
    label.setBounds(250,50,250,20);
    this.setSize(500,500);
    this.setTitle("Platformer");
    this.setLayout(null);
    this.setResizable(false);
    this.setVisible(true);
    this.add(button);
    this.setDefaultCloseOperation(3);


}

@Override
public void actionPerformed(ActionEvent e) {
    if(e.getSource()==button){
        System.out.println("Starting...");
        NameHere.this.add(label);//Here it should add the label to the frame
    }
}
}

in this code in the function actionPerformed it should add the label but it didn't work but when I try to add it in my Namehere function it works.

camickr
  • 321,443
  • 19
  • 166
  • 288
CodeLect
  • 23
  • 4

1 Answers1

1

From the troubleshooting guide:

Add or Remove Components

When you add or remove components, you must manually invoke repaint or revalidate Swing and AWT.

Best invoke both, see Java Swing revalidate() vs repaint().

Now the code as mre:

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

public class NameHere extends JFrame implements ActionListener {
    JButton button = new JButton("Start");
    JLabel label = new JLabel("Starting the App");
    NameHere() {
        button.setBounds(212,235,75,30);
        button.addActionListener(this::actionPerformed);
        label.setBounds(250,50,250,20);
        this.setSize(500,500);
        this.setTitle("Platformer");
        this.setLayout(null);
        this.setResizable(false);
        this.setVisible(true);
        this.add(button);
        this.setDefaultCloseOperation(3);
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        if(e.getSource()==button){
            System.out.println("Starting...");
            NameHere.this.add(label);//Here it should add the label to the frame
            revalidate();
            repaint();
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new NameHere();
            }
        });
    }
}
Franck
  • 1,340
  • 2
  • 3
  • 15