Question

When I add Button Action listener which should add textarea below the buttons in my window, it won't work.

The compiler (Netbeans) suggest to go with the final variable but nothing happens, so obviously somethings wrong with the code below.

GOAL: When user clicks first button (Add user) it should give him the textfield to input name, password and email etc...

CODE:

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        LayoutManager layOut = new FlowLayout(FlowLayout.CENTER);
        Frame f = new Frame();
        f.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
});
        f.setLayout(layOut);
        Label lab = new Label("Welcome to the new program for user management, click the desirable action in this window: ",Label.CENTER);
        Button b1 = new Button("Add User");
        Button b2 = new Button("View all");
        Button b3 = new Button("Edit User");
        Button b4 = new Button("Remove User");
        Button b5 = new Button("Gooo");
        f.add(lab);
        f.add(b1);
        f.add(b2);
        f.add(b3);
        f.add(b4);
        f.setSize(600,600);
        f.setVisible(true);

        b1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                TextField tf = new TextField("This is my text field");
                f.add(tf);
            }
        });   
    }}
Was it helpful?

Solution

If you make f final and also call f.revalidate() after you add the TextField, you will see your text fields appear.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top