Naame Nameee Naame Nameee - 1 month ago 5
Java Question

Java Button adds label when clicked after being reized or dragged or something

I have a simple code here which adds a label after being clicked. it works fine, but in order to the label to be added i have to drag or reize the window after clicking the button.

Here is my code:

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class server01 extends Applet implements ActionListener {
Label helloLabel = new Label("applet v 0.0.1 | created for testing purpose");
Label hello2Label = new Label("this applet will be up-to-date.");
Button buttonButton = new Button("START" + " Button");
Label buttonLabel = new Label("Starting server...");

private static final long serialVersionUID = 1L;

public void init() {
setBackground(Color.black);
setForeground(Color.white);
buttonButton.setForeground(Color.black);
add(helloLabel);
add(hello2Label);
add(buttonButton);
buttonButton.addActionListener(this);
}

public void actionPerformed(ActionEvent e) {
if (e.getSource() == buttonButton) {
add(buttonLabel);
}
}
}

Answer

You need to call the validate method after making gui changes so that the applet can check if it is still rendered correctly. Doing a resize will basically do the same thing.

public void actionPerformed(ActionEvent e) {
        if (e.getSource() == buttonButton) {
            add(buttonLabel);
            validate();
        }
}
Comments